我通常使用與[XmlRoot]一個「佔位符」類,[的XmlElement],[XmlAttribute]和予有傳遞到解串器,其使我有佔位符的類型的對象的XML。一旦完成,剩下的唯一事情就是對強類型對象進行一些基本的數據綁定。
下面是一個簡單的類,是「支持XML」:
[XmlRoot(ElementName = "Car", IsNullable = false, Namespace="")]
public class Car
{
[XmlAttribute(AttributeName = "Model")]
public string Model { get; set; }
[XmlAttribute(AttributeName = "Make")]
public string Make { get; set ;}
}
這裏是如何從一個文件中正確反序列化:
public Car ReadXml(string fileLocation)
{
XmlSerializer carXml = new XmlSerializer(typeof(Car));
FileStream fs = File.OpenRead(fileLocation);
Car result = imageConfig.Deserialize(fs) as Car;
return result;
}
當然,你可以更換的FileStream由MemoryStream直接從內存中讀取Xml。
一旦在HTML,它會轉化爲這樣的事情:
<!-- It is assumed that MyCar is a public property of the current page. -->
<div>
Car Model : <%= MyCar.Model %> <br/>
Car Make : <%= MyCar.Make %>
</div>