Simple deserialization of XML to C# object

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);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章