0
<career code="17-1011.00">
   <code>17-1011.00</code>
   <title>Architects</title>
   <tags bright_outlook="false" green="true" apprenticeship="false" />
   <also_called>
      <title>Architect</title>
      <title>Project Architect</title>
      <title>Project Manager</title>
      <title>Architectural Project Manager</title>
   </also_called>
   <what_they_do>Plan and design structures, such as private residences, office buildings, theaters, factories, and other structural property.</what_they_do>
   <on_the_job>
      <task>Consult with clients to determine functional or spatial requirements of structures.</task>
      <task>Prepare scale drawings.</task>
      <task>Plan layout of project.</task>
   </on_the_job>
</career>

我已经获取了从 ONet 返回的这个 XML,并希望解析要使用的信息。这是我编写的代码,用于尝试解析 下标签的内部文本,“输入”是 Onet XML。

 XmlDocument inputXML = new XmlDocument();
        inputXML.LoadXml(input);
        XmlElement root = inputXML.DocumentElement;
        XmlNodeList titleList = root.GetElementsByTagName("also_called");
        for (int i = 0; i < titleList.Count; i++)
        {
            Console.WriteLine(titleList[i].InnerText);
        } 

我期待一个大小为 4 的 NodeList。但是,当我打印出结果时,结果的大小为 1:“ArchitectProject ArchitectProject ManagerArchitectural Project Manager”

我是否构建了我的 XMLNodeList titleList 错误?如何进一步遍历和处理 XML 树以获取“also_call”下的“标题”标签的内部值?

4

2 回答 2

2

你得到了命名的元素also_called。您的列表中只有一个这样的元素。您可能想要的是获取节点的子also_called节点。

例如:

XmlNodeList also_calledList = root.GetElementsByTagName("also_called");
XmlNode also_calledElement = also_calledList[0];
XmlNodeList titleList = also_calledElement.ChildNodes;

foreach (XmlNode titleNode in titleList)
{
    Console.WriteLine(titleNode.InnerText);
}

此外,请考虑使用XDocumentLINQ to XML 而不是XmlDocument- 它使用起来要简单得多:

XDocument root = XDocument.Parse(input);

foreach (XElement titleNode in root.Descendants("also_called").First().Elements())
{
    Console.WriteLine(titleNode.Value);
}
于 2014-04-11T19:06:22.887 回答
0

您只需要一点 XPath。这将选择所有title作为 first 子节点的节点also_called

        XmlDocument inputXML = new XmlDocument();
        inputXML.LoadXml(input);

        foreach(var node in root.SelectNodes("also_called[1]/title"))
        {
            Console.WriteLine(node.InnerText);
        } 

您很少需要使用GetElementsByTagNameorChildNodes及其同类和/或尝试检查节点以确定它是否是您想要的节点。使用Xml 导航XmlDocument就是使用XPath,在获取满足特定条件的节点时,您可以指定相当多的内容;在树内的结构和内容方面。

于 2014-04-11T19:24:35.147 回答