文章目录
Simple deserialization of XML to C# object
1. Prepare XML string
string xmlString = @"
<Products>
<Product>
<Id>1</Id>
<Name>My XML product</Name>
</Product>
<Product>
<Id>2</Id>
<Name>My second product</Name>
</Product>
</Products>";
2. Prepare C# object
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
3. Create XML serializer
First argument is type of object you want to get and in second argument you specify root attribute of your XML source.
XmlSerializer serializer = new XmlSerializer(typeof(List<Product>)
, new XmlRootAttribute("Products"));
注意需要引入命名空间
using System.Xml; using System.Xml.Serialization;
4. Create StringReader object
StringReader stringReader = new StringReader(xmlString);
注意需要引入命名空间
using System.IO;
5. Finally, deserialize to your C# object
You can use our StringReader as argument or StreamWriter for external xml file too.
List<Product> productList = (List<Product>)serializer.Deserialize(stringReader);