select elements with the name attribute name in special xml structure

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-02 06:45:59

问题


below is the structure of my xml document. I just want to first take the value of every node <attribute name="a"> then make a comparison of it with a given value. However I don't how to locate <attribute name="a"> of each node using xml selectnodes in c#. Google searches don't show any working solutions.

<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>     

回答1:


Assuming the XML markup in your question represents your whole document, you can do:

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



回答2:


Use Linq to XML:

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

To retrieve the values instead of the nodes:

var myValues = xml.Descendants("attribute")
                  .Where(x => x.Attribute("name").Value == "a")
                  .Select(x => x.Value);



回答3:


You could use Linq to XML, something like the following:

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

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

You could then loop through the results as required.

There is a nice Linq to XML overview here too.




回答4:


I like to use the System.Xml.XmlDocument class for my xml parsing.

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

You should have a look at some XPath reference to be sure that you're getting the xpath string right http://msdn.microsoft.com/en-us/library/ms256086.aspx



来源:https://stackoverflow.com/questions/8898121/select-elements-with-the-name-attribute-name-in-special-xml-structure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!