给出一些示例XML,例如:
<XML>
<EMPLOYEES>
<EMPLOYEE isBestEmployee="false">John"<"/EMPLOYEE>
<EMPLOYEE isBestEmployee="true">Joe"<"/EMPLOYEE>
<EMPLOYEE isBestEmployee="false">Bill"<"/EMPLOYEE>
</EMPLOYEES>
</XML>
如何将isBestEmployee="true"
的员工序列化为单个Employee对象?
答案 0 :(得分:1)
我对这个问题有两个答案,这是第二个答案:
鉴于任何列表,您如何找到特定值?
您只需要解析列表。
现在,我假设你不确定如何做到这一点:
[XmlType("EMPLOYEES"), Serializable]
public class Employees {
public Employee[] employee {get; set;}
}
[XmlType("EMPLOYEE")]
public class Employee {
[XmlAttribute("isBestEmployee")]
public bool bestEmployee {get; set;}
[XmlText]
public string name;
}
您应该反序列化(可能使用XmlSerializer
),然后您可以使用foreach (Employee in Employees)
或LINQ查询或任何其他方式解析数组。
这是否回答了这个问题?
答案 1 :(得分:0)
我对这个问题有两个答案,这是第一个答案:
http://www.csharp-examples.net/xml-nodes-by-attribute-value/
答案 2 :(得分:0)
你指的是这样的事情(也许linq做了沉重的事情)?
XDocument loaded = XDocument.Load(@"C:\YourXmlFile.xml"); //or xml in memory
// Query the data and create the employee objects
var q = from c in loaded.Descendants("EMPLOYEE")
where (bool)c.Attribute("isBestEmployee") == true //"true"
select new Employee() { Name = c.Value, isBestEmployee = (bool)c.Attribute("isBestEmployee") };
//print out the list of employees if you want.
foreach (Employee e in q)
{
Console.WriteLine("Employee name = {0}, isBestEmployee = {1}", e.Name, e.isBestEmployee);
}