Caliber Caliber - 1 month ago 14
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

Product
where
Id=2
and add it to
productList
?

The Class:

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


Code:

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

Answer

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.

Comments