2013-08-19 226 views
0

我有XML文檔:LINQ XML子元素/節點

<users> 
     <user_tuple> 
      <userid>U01</userid> 
      <code> 
      <name>Tom Jones</name> 
      </code> 
      <rating>B</rating> 
     </user_tuple> 
     <user_tuple> 
      <userid>U02</userid> 
      <code> 
      <name>Mary Doe</name> 
      </code> 
      <rating>A</rating> 
     </user_tuple> 
     <user_tuple> 
      <userid>U03</userid> 
      <code> 
      <name>Dee Linquent</name> 
      </code> 
     <rating>D</rating> 
     </user_tuple> 

如何,我只選擇那些(和所有子節點/元素)其中userid.Value == 「U01」 和評級.value的== 「B」 等 即我想要的結果:

<user_tuple> 
     <userid>U01</userid> 
     <code> 
     <name>Tom Jones</name> 
     </code> 
     <rating>B</rating> 
    </user_tuple> 

回答

0

這應該工作(在C#),嘗試一下

string id = "U01"; 
string rating = "B"; 
XDocument doc = null; 
using (var reader1 = new StreamReader(@"..\..\test.xml")) 
{ 
    doc = XDocument.Load(reader1); 
    var nodes = from c in doc.Descendants("user_tuple") 
          .Where(d => d.Element("userid").Value == id && d.Element("rating").Value == rating) 
       select c; 
} 
+0

Thnx。如果選擇x.Element(「userid」)。Value ==「U01」and x.Element(「name」)。Value ==「Tom Jones」? –

0

您只需要Userid和rating匹配的值。這裏是代碼

XElement root = XElement.Load(@"YOUR XML PATH"); 
     var res = root.Elements("user_tuple").Where(x => x.Element("userid").Value == "U01" && x.Element("rating").Value == "B").Elements(); 
+0

使用命名空間** System.XML.Linq ** – Jagadesh

+0

Thnx。如果選擇x.Element(「userid」)。Value ==「U01」and x.Element(「name」)。Value ==「Tom Jones」? –

+0

@ГарикГарик你會得到相同的 – Jagadesh