我是.net 菜鸟。
今天学习一下反序列化xml,即将xml文件转换成程序更好识别的对象。
下面来看一个例子。这是一个xml文件。
<xml>
<students>
<student>
<fields>
<field value="name"><field>
<field value="id"></field>
</fields>
<contact value="phoneNumber">
<telephone type="number">urgent="number">urgent contactor's number</telephone>
<telephone type="number">urgent="number">>apartment number</telephone>
</contact>
</student>
</students>
</xml>
好了,这是一个比较简单的xml文件。
现在开始写反序列化的操作。
在你的实现类中写一个方法
public class ChangeXml{
public static T DeserializeObject<T>(string xml)
{
var str= new StringReader(xml);
var xmlSerializer= new XmlSerializer(typeof(T));
var result= (T)xmlSerializer.Deserialize(str);
return result;
}
}
[XmlType(TypeName = "xml")]
public class XmlElement
{
[XmlArray("Students", IsNullable = false)]
[XmlArrayItem("Student", IsNullable = false)]
public List<StudentElement> Students{ get; set; }
}
public class StudentElement
{
[XmlArray("fields", IsNullable = false)]
[XmlArrayItem("field", IsNullable = false)]
public List<FieldElement> fields{ get; set; }
[XmlArray("contact", IsNullable = false)]
[XMLAttribute("value")
public string value{get;set;}
[XmlArrayItem("telephone", IsNullable = false)]
public List<PhoneElement> contact{ get; set; }
}
public class PhoneElement
{
[XmlAttribute("type")]
public string type{ get; set; }
[XmlText]
public string Value { get; set; }
}
最后调用DeserializeObject<XmlElement>()方法就行了