简体   繁体   中英

C# XML Serialisation Only Serialise Single Element in List

Given some sample XML such as:

<XML>  
  <EMPLOYEES>    
    <EMPLOYEE isBestEmployee="false">John"<"/EMPLOYEE>  
    <EMPLOYEE isBestEmployee="true">Joe"<"/EMPLOYEE>  
    <EMPLOYEE isBestEmployee="false">Bill"<"/EMPLOYEE>  
  </EMPLOYEES>  
</XML>  

How do I serialise just the employee with isBestEmployee="true" to a single Employee object?

I have two answers for this question, here's the second answer:

Given any list, how do you find a specific value?

You just have to parse the list.


Now, I'll assume you're not sure how to do that:

[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;
}

You should deserialize this (probably with XmlSerializer ) and then you can parse the array using foreach (Employee in Employees) or a LINQ query or any of a number of other ways.

Does this answer the question?

I have two answers for this question, here's the first answer:

http://www.csharp-examples.net/xml-nodes-by-attribute-value/

Are you referring to something like this (maybe have linq do the heavy lifting)?

 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);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM