Getting a child element from a specific element

Tucalipe

Member
Joined
Jul 7, 2017
Messages
8
Programming Experience
Beginner
I've been suggested to work with LINQ rather than serializing when working with settings xml files.

According to the reference (https://docs.microsoft.com) I can use the following to get the value of a specific element:

C#:
string grandChild3 = (string)      (from el in root.Descendants("GrandChild3")  
    select el).First();  
return grandChild3

Their example XML:

C#:
<Root>    <Child1>  
    <GrandChild1>GC1 Value</GrandChild1>  
  </Child1>  
  <Child2>  
    <GrandChild2>GC2 Value</GrandChild2>  
  </Child2>  
  <Child3>  
    <GrandChild3>GC3 Value</GrandChild3>  
  </Child3>  
  <Child4>  
    <GrandChild4>GC4 Value</GrandChild4>  
  </Child4>  
</Root>

This method would return me a string with <root><child3><GrandChild3>'s value.

However, the XML I'm working with follows this structure:

C#:
<root>
    <section1>
        <setting1>
        <setting2>
        <setting3>
    </section1>
    <section2>
        <setting1>
        <setting4>
        <setting5>
    </section2>
</root>

A spoof of my code:
C#:
string grandChild3 = (string)      (from el in root.Descendants("setting1")  
    select el).First();  
return setting1
By using el.First, I'll only get the very first <setting1> value. If I don't use .First, I'll get a list of all <setting1>'s. How can I specifically refer to the <setting1> element located in <section2> (or any other section, for that matter).
 
Last edited:
Access by Element:
var sample = root.Element("section2").Element("setting1").Value;
 
Back
Top Bottom