且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#中的LINQ to XML查询

更新时间:2023-02-17 17:14:49

  VAR的结果= xdoc.Descendants(世界)
.Descendants(动物)
.Descendants(标签)
.Elements(狗)
。其中(n =方式> n.Attribute(ID)值==1);



输出:



<狗ID =1>
< D​​OG1>< / DOG1>
<&DOG2 GT;< / DOG2>
< D​​og3>< / Dog3>
< /狗>


<World>
  <Animals>
    <Tab>
      <Dogs id ="1">
        <Dog1></Dog1>
        <Dog2></Dog2>
        <Dog3></Dog3>
      </Dogs>
      <Dogs id ="2"></Dogs>
      <Dogs id ="3"></Dogs>
    </Tab>
  </Animals>
</World>

How do I get all elements under tag where id == 1?

My Linq query. (doesn't work) why?

XDocument xml= XDocument.Load(xml.xml);
var elements = from e in xml.Descendants("Animals").Descendants("Tab").Elements("Dogs")
where e.Attribute("id").toString().Equals("1")
select c;

Could you check it please?

Thanks!

var result = xdoc.Descendants("World")
                 .Descendants("Animals")
                 .Descendants("Tab")
                 .Elements("Dogs")
                 .Where(n => n.Attribute("id").Value == "1");

Output:

<Dogs id="1">
  <Dog1></Dog1>
  <Dog2></Dog2>
  <Dog3></Dog3>
</Dogs>