Search code examples
c#xmllinqxelement

Get the XElement for the XML


Here's my XML File:

<Applications>
   <Application Name="Abc">
     <Section Name="xyz">
        <Template Name="hello">
         ...
         ....
         </Template>
      </Section>
   </Application>
   <Application Name="Abc1">
     <Section Name="xyz1">
        <Template Name="hello">
         ...
         ....
         </Template>
      </Section>
   </Application>

What I need to do is get the Template XElement from the given structure based upon the Name attribute of Template tag. The problem is there can be multiple template tags with same attribute Name. The Distinguishing factor is Application Name attribute value and section attribute value.

Currently I'm able to get the XElement by first getting Application Element based upon it's attribute, then Section based upon it's attribute and then finally template based upon it' name.

I wanted to know if there is a way to get it in one go.


Solution

  • The following code should do the trick:

    var template = doc.Descendants("Template")
                      .Where(x => x.Attribute("Name").Value == "hello"
                               && x.Parent.Attribute("Name").Value == "xyz1"
                               && x.Parent.Parent.Attribute("Name").Value == "Abc1");
    

    Please note that this code throws exceptions if the XML doesn't conform to the specification. Specifically, there will be a NullReferenceException if any of the tags in question don't contain an attribute named "Name". Or if the Template tag doesn't have two levels of parents.