使用C#解析内部XML标记

本文关键字:XML 标记 内部 使用 | 更新日期: 2023-09-27 17:58:01

<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,并希望解析要使用的信息。以下是我编写的代码,用于尝试和解析下面标记的内部文本,其中"input"是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:"建筑项目建筑师项目经理建筑项目经理">

我是否构建了错误的XMLNodeList标题列表?如何进一步遍历和处理XML树以获得"also_called"下"title"标记的内部值?

使用C#解析内部XML标记

您将获得名为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到XML而不是XmlDocument——使用起来要简单得多:

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

您只需要一点点XPath。这选择了作为第一CCD_ 6的子节点的所有CCD_。

        XmlDocument inputXML = new XmlDocument();
        inputXML.LoadXml(input);
        foreach(var node in root.SelectNodes("also_called[1]/title"))
        {
            Console.WriteLine(node.InnerText);
        } 

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