2012-05-16 21 views
0

我有一个包含以下内容(myfile.xml)的文件。我必须得到所有内容(包括产品节点)id=1的产品。通过属性从xml获取数据vlaue

<products> 
    <product id="1"> 
     <category>q</category> 
    </product>  
    <product id="2">  
     <category>w</category>  
    </product> 
    <product id="3">  
    <category>e</category> 
</product> 
</products>` 

即结果应该是:

<product id="1"> 
     <category>q</category> 
    </product> 

我怎样才能做到这一点?

+0

后续[使用的XmlTextReader](http://stackoverflow.com/questions/10680553/getting-data-from-xml-by-attribute-value-c -sharp-使用-XmlTextReader的) –

回答

0
var root = XElement.Load("path to the file"); 
var node = root.Descendants("product").FirstOrDefault(e=>e.Attribute("id").Value == "1"); 
1

使用XPath in Linq

var root = XElement.Load("myfile.xml"); 
root.XPathSelectElements("/products/product[@id=1]");