我有这样的 xml 文档:
<level1>
<level2>
<level3>
<attribute1>...</attribute1>
<attribute2>false</attribute2>
<attribute3>...</attribute3>
</level3>
<level3>
<attribute1>...</attribute1>
<attribute2>true</attribute2>
<attribute3>...</attribute3>
</level3>
</level2>
<level2>
<level3>
<attribute1>...</attribute1>
<attribute2>false</attribute2>
...
...
...
我正在使用 C#,我想遍历所有“level3”,对于每个“level3”,我想读取 attribute2,如果它说“true”,我想打印相应的 attribute3(可以没有这些属性是“level3”)。
我将 xml 保存在 XmlDocument 中。 然后我像这样保留所有“level3”节点:
XmlNodeList xnList = document.SelectNodes(String.Format("/level1/level2/level3"));
(文档是 XmlDocument)。
但从现在开始,我不知道该如何继续。我尝试使用 for..each 通过 xnList,但对我来说没有任何效果..
我该怎么做?
非常感谢
请您参考如下方法:
我会使用 LINQ to XML:
var results = from level3 in doc.Descendants("level3")
where (bool) level3.Element("attribute2")
select level3.Element("attribute3").Value;
foreach (string result in results)
{
Console.WriteLine(result);
}
与 XmlDocument API 相比,LINQ to XML 使各种事情很多变得简单。当然,缺点是它需要.NET 3.5...
(顺便说一句,elements attributeN 的命名有点令人困惑...人们会期望 attribute 指的是实际的 XML 属性...)
