如何使用Linq填充XML?

时间:2014-03-06 21:47:44

标签: xml linq

如何使用LINQ和以下XML

填充person对象
<Results> 
  <Person name="Edwin"> 
    <DOB>1990-10-01</DOB>
    <Department>Engineering</Department> 
  </Person> 
  <Person name="Joe">
    <DOB>1979-10-01</DOB> 
    <Department>Engineering</Department> 
  </Person>
  <Person name="Eric"> 
    <DOB>1989-10-01</DOB>
    <Department>Sales</Department> 
  </Person>
</Results>

1 个答案:

答案 0 :(得分:1)

假设是

public class Person
{
    public string Name { get; set; }
    public DateTime DateOfBirth { get; set; }
    public string Department { get; set; }
}

解析:

var xdoc = XDocument.Load(path_to_xml);
var people = from p in xdoc.Root.Elements("Person")
             select new Person {
                 Name = (string)p.Attribute("name"),
                 DateOfBirth = (DateTime)p.Element("DOB"),
                 Department = (string)p.Element("Department")
             };

您也可以使用xml反序列化。添加序列化属性:

public class Results
{        
    [XmlElement("Person")]
    public List<Person> People { get; set; }
}

public class Person
{
    [XmlAttribute("name")]
    public string Name { get; set; }
    [XmlElement("DOB")]
    public DateTime DateOfBirth { get; set; }
    public string Department { get; set; }
}

反序列化结果:

XmlSerializer serializer = new XmlSerializer(typeof(Results));
var results = (Results)serializer.Deserialize(File.OpenRead(path_to_xml));
var people = results.People;