linq xml选择节点

时间:2013-08-19 18:11:10

标签: 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”和元素(“name”)。值==“Tom Jones”等即我想要结果:

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

我正在使用C#

public void searchInfo(string rootNode, string Element1Name, string Element2Name,  string Element1Val, string Element2Val){ 

////// Select rootNode and all descend nodes

    var res = root.Elements("rootNode")
       .Where(
          x => 
             (string)x.Element(Element1Name) == Element1Val&&
             (string)x.Element(Element2Name) == Element2Val)
       ).ToList();
///////////    

foreach (var node in res){
 Debug.Writeline("Name {0} Value {1}", node.Name, node.Value)

}

示例:

searchInfo(“rootNode”,“userid”,“code”,“U01”,“Tom Jones”)

res =  <userid>U01</userid>
          <code>
            <name>Tom Jones</name>
          </code>
          <rating>B</rating>

and result:
userid U01
name Tom Jones 
rating B

这可能吗?

1 个答案:

答案 0 :(得分:1)

试试这个

var doc = XDocument.Parse(s);
var res = doc.Elements("users").Elements("user_tuple")
   .Where(
      x => 
         (string)x.Element("userid") == "U01" &&
         (string)x.Element("code").Element("name") == "TomJones")
   ).ToList();

或者使用XPath:

var res = doc.XPathSelectElements("
                users/user_tuple[userid='U01' and code[name='TomJones']]
          ").ToList();