linq xml子元素/节点

时间:2013-08-19 11:55:02

标签: 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”和rating.Value ==“B”等 即我想要结果:

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

2 个答案:

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

答案 1 :(得分:0)

您只需要Userid和评级匹配的值。这是代码

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();