Hamid Reza
Hamid Reza

Reputation: 2973

How to get specific children of a xml element?

I am loading a xml document and I am having a foreach loop in its elements and I want to select child elements named tag in it.

This is the xml file:

<?xml version="1.0" encoding="utf-8"?>
<view>
    <tag>
      <name>content</name>
      <tag>
        <name>div</name>
      </tag>
    </tag>
</view>

And this is the code:

string xmlString = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("~/xml/xml.xml"));
XDocument doc = XDocument.Parse(xmlString);
XElement xmlElement = doc.Element("view");
foreach (var tagItem in xmlElement.Descendants("tag"))
{
    //do something
}

The code written in foreach loop would contain all of tag elements in any depth, but I want to get the first depth ones(the children).

How to do this with linq?

Upvotes: 3

Views: 7537

Answers (1)

helb
helb

Reputation: 7773

Assuming the desired elements are always children of the <view> element you can use:

XElement xmlElement = doc.Element("view");
foreach (var tagItem in xmlElement.Elements("tag"))
{
    //do something (only direct children)
}

There is nothing more to be done to get the desired elements. You can then however implement your "do something" with Linq, for example:

XElement firstElem = xmlElement.Elements("tag").OrderBy(e => e.Name).First();

Upvotes: 3

Related Questions