Caliber Caliber - 3 months ago 17
C# Question

Deserialize only specific item from XML and add to list

I've got an XML file with multiple items, and I want to deserialize only a single specific one at a time, rather than all of them, and add it to a list.

Using the example from this site, how do I deserialize only the

and add it to

The Class:

public class Product
public int Id { get; set; }
public string Name { get; set; }


void foo()
string xmlString = "<Products><Product><Id>1</Id><Name>My XML product</Name></Product><Product><Id>2</Id><Name>My second product</Name></Product></Products>";

XmlSerializer serializer = new XmlSerializer(typeof(List<Product>), new XmlRootAttribute("Products"));

StringReader stringReader = new StringReader(xmlString);

List<Product> productList = (List<Product>)serializer.Deserialize(stringReader);


You can use the XDocument class to query Xml:

StringReader stringReader = new StringReader(xmlString);
XDocument document = XDocument.Load(stringReader);

var node = document.Descendants("Product").FirstOrDefault(p => p.Descendants("Id").First().Value == "2");
if(node != null)
    XmlSerializer serializer = new XmlSerializer(typeof(Product));
    var xmlReader = new StringReader(node.ToString());
    Product result = serializer.Deserialize(xmlReader) as Product;

Granted, this is a quick and dirty solution that may require further analysis for certain situations.