在特殊的xml结构中选择具有name属性name的元素
下面是我的xml文档的结构。 我只想先取每个节点的值,然后将它与给定值进行比较。 但是,我不知道如何使用c#中的xml selectnodes找到每个节点的
。 Google搜索未显示任何有效的解决方案。
This is node1 a This is node1 b This is node2 a This is node2 b ...
假设您的问题中的XML标记代表您的整个文档,您可以执行以下操作:
XmlNodeList attrElements = yourDocument.SelectNodes("/nodes/node/attribute[@name='a']");
使用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);
您可以使用Linq to XML,如下所示:
string xml = "..."; var results = from node in XDocument.Parse(xml).Descendants() where node.Name == "attribute" select node.Value;
然后,您可以根据需要循环遍历结果。
这里也有一个很好的Linq to XML概述 。
我喜欢使用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