C#遍历多个xml节点(和子节点)并写入对象

时间:2017-01-14 10:09:46

标签: c# xml iteration nodes

我有一个Person类(Name,Adress,Car,List)和一个带有这些值的XML文档:

<person>
  <Name>Miller</name>
  <Car>BMW</car>
</person>
<person>
  <name>Smith</name>
  <adress>New York</adress>
  <Pets>
    <pet>Cat</pet>
    <pet>Dog</pet>
  </pets>
</person>....

如何遍历这些节点和子节点(以及子节点,如果可用,以及子节点......)并将其全部写入我的列表?

谢谢

1 个答案:

答案 0 :(得分:0)

使用xml linq。您可以通过使用Load()方法替换Parse()方法从文件加载:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;

namespace ConsoleApplication42
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml =
              "<Root>" +
              "<person>" +
                "<name>Miller</name>" +
                "<car>BMW</car>" +
              "</person>" +
              "<person>" +
                "<name>Smith</name>" +
                "<address>New York</address>" +
                "<pets>" +
                  "<pet>Cat</pet>" +
                  "<pet>Dog</pet>" +
                "</pets>" +
              "</person>" +
              "</Root>";

            XDocument doc = XDocument.Parse(xml);
            Person.people = doc.Descendants("person").Select(x => new Person() {
                name = (string)x.Element("name"),
                car = (string)x.Element("car"),
                address = (string)x.Element("address"),
                pets = x.Descendants("pet").Select(y => (string)y).ToList()
            }).ToList();
        }

    }
    public class Person
    {
        public static List<Person> people { get; set; }
        public string name { get; set; }
        public string car { get; set; }
        public string address { get; set; }
        public List<string> pets { get; set; }
    }


}