3

下面是我的 xml 文档的结构。我只想先获取每个节点的值,<attribute name="a">然后将其与给定值进行比较。但是我不知道如何<attribute name="a">在 c# 中使用 xml selectnodes 来定位每个节点。谷歌搜索没有显示任何有效的解决方案。

<nodes>     
 <node name = "node1">      
  <attribute name="a">This is node1 a</attribute>
  <attribute name="b">This is node1 b</attribute>
 </node>
 <node name = "node2">      
  <attribute name="a">This is node2 a</attribute>
  <attribute name="b">This is node2 b</attribute>
 </node>
 ...
</nodes>     
4

4 回答 4

4

您可以使用 Linq to XML,如下所示:

string xml = "<nodes>...";

var results = from node in XDocument.Parse(xml).Descendants()
          where node.Name == "attribute"
          select node.Value;

然后,您可以根据需要循环遍历结果。

这里也有一个不错的Linq to XML 概述

于 2012-01-17T16:29:51.607 回答
3

使用 Linq 转 XML:

XElement xml = XElement.Load("test.xml");
var myNodes = xml.Descendants("attribute")
                 .Where(x => x.Attribute("name").Value == "a");

要检索值而不是节点:

var myValues = xml.Descendants("attribute")
                  .Where(x => x.Attribute("name").Value == "a")
                  .Select(x => x.Value);
于 2012-01-17T16:28:53.283 回答
2

假设您问题中的 XML 标记代表您的整个文档,您可以执行以下操作:

XmlNodeList attrElements
    = yourDocument.SelectNodes("/nodes/node/attribute[@name='a']");
于 2012-01-17T16:29:27.153 回答
1

我喜欢使用System.Xml.XmlDocument该类进行 xml 解析。

XmlDocument doc = new XmlDocument();
doc.load("myfilename.xml");
XmlNode node = doc.SelectSingleNode("\\attribute[name='a']")

您应该查看一些 XPath 参考,以确保您获得了正确的 xpath 字符串http://msdn.microsoft.com/en-us/library/ms256086.aspx

于 2012-01-17T16:32:47.400 回答