繁体   English   中英

使用C#解析内部XML标签

[英]Inner XML tag Parsing Using C#

<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 Architect ArchitectProject ManagerArchitectural Project Manager”

我是否将XMLNodeList titleList构造错误? 如何进一步遍历和处理XML树,以获取“ also_drawn”下“ title”标签的内部值?

您将获得名为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);
}

另外,考虑使用XDocument和LINQ to XML而不是XmlDocument使用起来简单得多:

XDocument root = XDocument.Parse(input);

foreach (XElement titleNode in root.Descendants("also_called").First().Elements())
{
    Console.WriteLine(titleNode.Value);
}

您只需要一点点XPath。 这样会选择所有title节点,它们是第一个also_called子节点。

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

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

很少需要使用GetElementsByTagNameChildNodes及其ChildNodes和/或尝试检查一个节点以弄清楚它是否是您想要的那个节点。 使用XmlDocument导航Xml就是要使用XPath ,在获取满足特定条件的节点时,可以使用XPath进行大量指定。 无论是在树内的结构还是在内容上。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM