需要对当前 xml 文档中的数据进行反序列化。我拿了完成的 xml 文件:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<address>24</address>
<city>New-York</city>
<state>Alabama</state>
<firstPerson>
<age>19</age>
<name>Jey</name>
<department>none</department>
</firstPerson>
<secondPerson>
<age>22</age>
<name>Abraham</name>
<department>none</department>
</secondPerson>
</root>
并基于它生成模型
[XmlRoot(ElementName="firstPerson")]
public class FirstPerson {
[XmlElement(ElementName="age")]
public string Age { get; set; }
[XmlElement(ElementName="name")]
public string Name { get; set; }
[XmlElement(ElementName="department")]
public string Department { get; set; }
}
[XmlRoot(ElementName="secondPerson")]
public class SecondPerson {
[XmlElement(ElementName="age")]
public string Age { get; set; }
[XmlElement(ElementName="name")]
public string Name { get; set; }
[XmlElement(ElementName="department")]
public string Department { get; set; }
}
[XmlRoot(ElementName="root")]
public class Root {
[XmlElement(ElementName="address")]
public string Address { get; set; }
[XmlElement(ElementName="city")]
public string City { get; set; }
[XmlElement(ElementName="state")]
public string State { get; set; }
[XmlElement(ElementName="firstPerson")]
public FirstPerson FirstPerson { get; set; }
[XmlElement(ElementName="secondPerson")]
public SecondPerson SecondPerson { get; set; }
}
由于参数(年龄等)相同,所以我重新做了数据模型
[Serializable]
[XmlRoot(ElementName="root")]
public class People
{
public byte Address { get; set; }
public string City { get; set; }
public string State { get; set; }
[XmlElement(ElementName = "firstPerson")]
public Person FirstPerson { get; set; }
[XmlElement(ElementName = "secondPerson")]
public Person SecondPerson { get; set; }
}
[Serializable]
[XmlRoot(ElementName = "root")]
public class Person
{
public byte Age { get; set; }
public string Name { get; set; }
public string Department { get; set; }
}
然后我读了xml:
internal class Program
{
private const string xmlPath = "test.xml";
private static void Main(string[] args)
{
var value = DeserializeSettings();
Console.WriteLine(value.Address);
Console.WriteLine(value.City);
Console.WriteLine(value.State);
Console.WriteLine(value.FirstPerson.Age);
Console.WriteLine(value.FirstPerson.Name);
Console.WriteLine(value.FirstPerson.Department);
Console.ReadKey();
}
private static People DeserializeSettings()
{
try
{
var serializer = new XmlSerializer(typeof(People));
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, xmlPath);
var reader = new StreamReader(path);
var people = (People) serializer.Deserialize(reader);
reader.Close();
return people;
}
catch (Exception e)
{
Console.WriteLine(e);
return new People();
}
}
}
返回所有属性一个属性
[XmlElement(ElementName="age")]
,依此类推。关键是 XML 区分大小写。也就是说,
Age
和age
是不同的节点。因此,您要么需要指定 attributes
XmlElement
,要么更改 C# 中的属性名称(但根据指南,它们必须以大写字母开头,因此您不应该这样做),或者更改 xml 本身。