读取XML文件 - 读取具有任意数量子节点的子节点

时间:2014-03-03 19:06:25

标签: c# xml

所以我当前正试图解析一个看起来像这样的XML文件:

<employees>
    <employee>
     <id>1</id>
         <projects>
            <projectID>7</projectID>
            <projectID>3</projectID>
         </projects>
    </employee>
    <employee>
     <id>2</id>
         <projects>
            <projectID>4</projectID>
         </projects>
    </employee>
</employees>

我正在尝试阅读每位员工和任何出现的项目。 Employee对象是一个字符串和列表(int)。

目前我有:

        XmlDocument doc = new XmlDocument();
        doc.Load(path);
        XmlNodeList xmlNodes = doc.DocumentElement.SelectNodes("/employees/employee");
        foreach (XmlNode xmlNode in xmlNodes)
        {
            string id;
            List<int> projects = new List<int>();

            id = xmlNode.SelectSingleNode("id").InnerText;

            //this is the bit. What I have works but it feels like it could
            //be majorly refined. Is there a better way to construct the foreach below?

            foreach (XmlNode node in xmlNode.ChildNodes.Item(1)) 
            //index 1 is the projects node
            {
                projects.Add(int.Parse(node.InnerText));
            }

            //

            Employee e = new Employee(id, projects);
            e.Add(e);
        }

如果XML文件本身存在问题,可以更改它以适应解析。

谢谢。

1 个答案:

答案 0 :(得分:1)

使用LINQ to XML会更容易:

var xDoc = XDocument.Load(path);
var employees = (from e in xDoc.Root.Elements("employee")
                 let projects = e.Element("projects")
                                 .Elements("projectID")
                                 .Select(p => (int)p)
                                 .ToList()
                 let id = (string)e.Element("id")
                 select new Employee(id, projects)).ToList();

您需要using System.Linqusing System.Xml.Linq才能使其正常运行。