.NET XML Deserialization
I have the following XML feed. I need to do deserialization to a List
of objects. How can 开发者_C百科I achieve this in .NET 4.0 C#?
<body>
<games>
<sports>
<lot_name>Football</lot_name>
<prizes>
<!-- For each prize the "division_" tag ends with different number -->
<divisions_1>
<divisions>1</divisions>
<match>5-2</match>
<pay>$10</pay>
</divisions_1>
<divisions_2>
<divisions>2</divisions>
<match>3-2</match>
<pay>$5</pay>
</divisions_2>
</prizes>
</sports>
</games>
</body>
Look at here, a good explanation.
xsd.exe is a handy little tool that comes with the .NET SDK (Software Development Kit) that can make life easy when you want to quickly go from an XML input to a strongly-typed .NET object.
If you're starting with an XML file:
1) Open the XML file in Visual Studio
2) From the XML menu click "Create Schema". This will generate a XSD file.
The rest here.
Take a look at THIS tutorial on how to do XML serialization, the example there is pretty near to yours.
Basically you need to create a class which represents each entity in your XML (e.g. Sports
) and the corresponding properties and then us an XmlSerializer to deserialze it.
The more complex way, but where you can handle the strange <division_X>
tags, would be to use an XmlReader
and read in the elements on your own and assign it to appropriate classes/objects.
Unless you want to generate a XSD with N division_x
elements where x = [1..N] you have to implement IXmlSerializable
. The following code does deserialize the example xml nicely:
public class Sports : IXmlSerializable
{
public string LotName { get; set; }
public List<dynamic> Prices { get; set; }
#region IXmlSerializable Members
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
Prices = new List<dynamic>();
reader.Read();
LotName = reader.ReadElementContentAsString("lot_name", "");
reader.Read();
while (reader.Name.StartsWith("divisions_"))
{
reader.Read();
var i = reader.ReadElementContentAsString("divisions", "");
var m = reader.ReadElementContentAsString("match", "");
var p = reader.ReadElementContentAsString("pay", "");
Prices.Add(new { ID = i, Match = m, Pay = p });
reader.Read();
}
}
public void WriteXml(System.Xml.XmlWriter writer)
{
throw new NotImplementedException();
}
#endregion
}
public class Games {
[XmlElement("sports")]
public Sports Sports { get; set; }
}
[XmlRoot("body")]
public class Body
{
[XmlElement("games")]
public Games Games { get; set; }
}
It uses XmlSerialization
because I am not quite sure how to do it with Data Contract Serializer
(I know it can be done though). And you might want to add some error handling to the ReadXml
method.
PS. You could do it with one class that implements XmlSerializer and emits a lot of dynamic classes :)
精彩评论