How do I Deserialize this XML document:
<?xml version="1.0" encoding="utf-8"?>
<Cars>
<Car>
<StockNumber>1020</StockNumber>
<Make>Nissan</Make>
<Model>Sentra</Model>
</Car>
<Car>
<StockNumber>1010</StockNumber>
<Make>Toyota</Make>
<Model>Corolla</Model>
</Car>
<Car>
<StockNumber>1111</StockNumber>
<Make>Honda</Make>
<Model>Accord</Model>
</Car>
</Cars>
I have this:
[Serializable()]
public class Car
{
[System.Xml.Serialization.XmlElementAttribute("StockNumber")]
public string StockNumber{ get; set; }
[System.Xml.Serialization.XmlElementAttribute("Make")]
public string Make{ get; set; }
[System.Xml.Serialization.XmlElementAttribute("Model")]
public string Model{ get; set; }
}
.
[System.Xml.Serialization.XmlRootAttribute("Cars", Namespace = "", IsNullable = false)]
public class Cars
{
[XmlArrayItem(typeof(Car))]
public Car[] Car { get; set; }
}
.
public class CarSerializer
{
public Cars Deserialize()
{
Cars[] cars = null;
string path = HttpContext.Current.ApplicationInstance.Server.MapPath("~/App_Data/") + "cars.xml";
XmlSerializer serializer = new XmlSerializer(typeof(Cars[]));
StreamReader reader = new StreamReader(path);
reader.ReadToEnd();
cars = (Cars[])serializer.Deserialize(reader);
reader.Close();
return cars;
}
}
that don't seem to work :-(
try this block of code if your .xml file has been generated somewhere in disk and if you have used
List<T>
:Note:
C:\serialize.xml
is my .xml file's path. You can change it for your needs.The following snippet should do the trick (and you can ignore most of the serialization attributes):
...
The idea is to have all level being handled for deserialization Please see a sample solution that solved my similar issue
The above XML is handled in two level
The Inner level
Same Way you need multiple level with
car as array
Check this example for multilevel deserializationYou have two possibilities.
Method 1. XSD tool
Suppose that you have your XML file in this location
C:\path\to\xml\file.xml
You can find it in
Start Menu > Programs > Microsoft Visual Studio 2012 > Visual Studio Tools
Or if you have Windows 8 can just start typing Developer Command Prompt in Start screencd /D "C:\path\to\xml"
xsd file.xml
xsd /c file.xsd
And that's it! You have generated C# classes from xml file in
C:\path\to\xml\file.cs
Method 2 - Paste special
Required Visual Studio 2012+
Edit > Paste special > Paste XML As Classes
And that's it!
Usage
Usage is very simple with this helper class:
All you have to do now, is:
See if this helps:
.
And failing that use the xsd.exe program that comes with visual studio to create a schema document based on that xml file, and then use it again to create a class based on the schema document.
I don't think .net is 'picky about deserializing arrays'. The first xml document is not well formed. There is no root element, although it looks like there is. The canonical xml document has a root and at least 1 element (if at all). In your example: