Justin Kauffman
Justin Kauffman

Reputation: 433

Extracting XElement children and grandchildren by name

I have an XElement (myParent) containing multiple levels of children that I wish to extract data from. The elements of interest are at known locations in the parent.

I understand that I am able to get a child element by:

myParent.Element(childName);

or

myParent.Element(level1).Element(childName);

I am having trouble figuring out how to do this if I want to loop through an array offor a list of elements that are at different levels, and looping through the list. For instance, I am interested in getting the following set of elements:

myParent.Element("FieldOutputs").Element("Capacity");
myParent.Element("EngOutputs").Element("Performance")
myParent.Element("EngOutputs").Element("Unit").Element("Efficiency")

How can I define these locations in an array so that I can simply loop through the array?

i.e.

string[] myStringArray = {"FieldOutputs.Capacity", "EngOutputs.Performance", "EngOutputs.Unit.Efficiency"};

for (int i=0; i< myArray.Count(); i++)
{
    XElement myElement = myParent.Element(myStringArray);
}

I understand that the method above does not work, but just wanted to show effectively what I am trying to achieve.

Any feedback is appreciated.

Thank you, Justin

Upvotes: 1

Views: 7129

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500515

While normally I'm reluctant to suggest using XPath, it's probably the most appropriate approach here, using XPathSelectElement:

string[] paths = { "FieldOutputs/Capacity", "EngOutputs/Performance", 
                   "EngOutputs/Unit/Efficiency"};

foreach (string path in paths)
{
    XElement element = parent.XPathSelectElement(path);
    if (element != null)
    {
        // ...
    }
}

Upvotes: 7

James Sulak
James Sulak

Reputation: 32447

The Descendants() method is what you're looking for, I believe. For example:

var descendants = myParent.Descendants();
foreach (var e in descendants) {
  ...
}

http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.descendants.aspx

Edit:

Looking at your question more closely, it looks like you may want to use XPathSelectElements()

var descendants = myParent.XPathSelectElements("./FieldOutputs/Capacity | ./EngOutputs/Performance | ./EngOutputs/Units/Efficency");

http://msdn.microsoft.com/en-us/library/bb351355.aspx

Upvotes: 0

Related Questions