I'm trying to deseaqralize this XML document into a list of Car objects, but it is coming up null.
Here's a sample XML document based on this post: How to Deserialize XML document
<?xml version="1.0" encoding="utf-8"?>
<Cars>
<car id="1">
<StockNumber>1020</StockNumber>
<Make>Nissan</Make>
<Model>Sentra</Model>
</car>
<car id="2">
<StockNumber>1010</StockNumber>
<Make>Toyota</Make>
<Model>Corolla</Model>
</car>
<car id="3">
<StockNumber>1111</StockNumber>
<Make>Honda</Make>
<Model>Accord</Model>
</car>
</Cars>
Required Classes:
[Serializable()]
public class Car
{
[System.Xml.Serialization.XmlAttribute("id")]
public int id { get; set; }
[System.Xml.Serialization.XmlElement("StockNumber")]
public string StockNumber { get; set; }
[System.Xml.Serialization.XmlElement("Make")]
public string Make { get; set; }
[System.Xml.Serialization.XmlElement("Model")]
public string Model { get; set; }
}
[Serializable()]
[System.Xml.Serialization.XmlRoot("Cars")]
public class Cars
{
[XmlArray("Cars")]
[XmlArrayItem("Car", typeof(Car))]
public List<Car> Car { get; set; }
}
Deserialize function:
public void ParseReturnXmlForVirtualEvent2()
{
Cars cars = null;
string path = @"E:\Projects\Newcars.xml";
XmlDocument pdoc = new XmlDocument();
pdoc.Load(path);
XDocument Doc = new XDocument();
Doc = XDocument.Parse(pdoc.OuterXml);
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(Cars));
System.Xml.XmlReader reader = Doc.CreateReader();
cars = (Cars)serializer.Deserialize(reader);
reader.Close();
//return cars;
}
Let me know if you need me to provide further details.
XmlDocumentand then using that to parse anXDocumentand then using that to create anXmlReader? Just create anXmlReaderusingXmlReader.Create(path). You are parsing into two unrelated XML DOM's and throwing away.