在特殊的xml结构中选择具有name属性name的元素

时间:2012-01-17 16:25:14

标签: c# xml selectnodes

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

<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 个答案:

答案 0 :(得分: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);

答案 1 :(得分:2)

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

XmlNodeList attrElements
    = yourDocument.SelectNodes("/nodes/node/attribute[@name='a']");

答案 2 :(得分:2)

您可以使用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 overview here

答案 3 :(得分: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