XML内容
<Persons>
<Person age="18" Value="123">
Tom
</Person>
</Persons>
模型类Class
using System.Xml.Serialization;
namespace WpfApp2
{
// NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
/// <remarks/>
[XmlRoot("Persons")]
public partial class Persons
{
/// <remarks/>
/// 这里的Person要对应XML里的Person,不可不同
/// [XmlAttribute("Value")] 如果使用在这里是错误的,[XmlAttribute("Value")]属性只能用于简单类型,不能用于复杂对象,如类。
public MY Person;
}
/// <remarks/>
public partial class MY
{
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public byte age;
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public string Value;
[System.Xml.Serialization.XmlTextAttribute()]
[XmlAttribute("Value")]
/// [XmlAttribute("Value")]属性只能用于简单类型,不能用于复杂对象,如类。
public string MyValue;
}
}
反序列化代码
using System;
using System.IO;
using System.Windows;
using System.Xml.Serialization;
namespace WpfApp2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
MDGXmlDeserialize(File.ReadAllText(@"D:\temp\my.xml"));
}
private void MDGXmlDeserialize(string pathXML)
{
using (StringReader sr = new StringReader(pathXML))
{
XmlSerializer xmldes = new XmlSerializer(typeof(Persons));
var obj = (Persons)xmldes.Deserialize(sr);
//XmlSerializer xmldesMy = new XmlSerializer(typeof(MyPersons));
//MyPersons myPersons = (MyPersons)xmldesMy.Deserialize(sr);
Console.WriteLine(obj.Person.age);
Console.WriteLine(obj.Person.Value);
}
}
}
}