题
<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:《建筑师项目建筑师项目经理建筑项目经理》
我构建的 XMLNodeList titleList 是否错误?如何进一步遍历和处理 XML 树以获取“also_used”下“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的wee。这选择了作为第一个世代odicetagcode的子项的所有世代odicetagcode节点。
XmlDocument inputXML = new XmlDocument();
inputXML.LoadXml(input);
foreach(var node in root.SelectNodes("also_called[1]/title"))
{
Console.WriteLine(node.InnerText);
}
.
很少见,您需要使用title
或also_called
及其ilk和/或尝试检查节点,以弄清楚它是否是您想要的。使用GetElementsByTagName
导航XML是全部关于使用 xpath 您可以使用它可以在其中指定相当一点获取符合特定标准的节点;无论是在树内的结构和内容方面。
不隶属于 StackOverflow