2
<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!

0

3 Answers 3

3
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>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you!! Problem was in n.Attiribute("id").VALUE. ( I forgot add .value)
1

Or use XPath:

xml.XPathSelectElements("/World/Animals/Tab/Dogs[@id=1]")

or

xml.XPathSelectElements("//Dogs[@id=1]")

which would find all Dogs wherever they occurred.

1 Comment

Only if you want Dogs outside of "Animals" too.
1

From your sample data I think you want

//from e in xml.Descendants("Animals").Descendants("Tab").Elements("Dogs")
from e in xml.Descendants("Animals").Elements("Tab").Descendants("Dogs")

And in the same line, Descendants("Animals") could be Elements("Animals") if you want to enforce the structure.

For the rest your query looks OK.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.