Query an XDocument for elements by name at any depth

Query an XDocument for elements by name at any depth

Asked on December 24, 2018 in XML.
Add Comment


  • 3 Answer(s)

    Query an XDocument for elements by name at the depth:

         Descendants should work as good,

    using System;
    using System.Xml.Linq;
     
    class Test
    {  
        static void Main()
        {
            string xml = @"
    <root>
      <child id='1'/>
      <child id='2'>
        <grandchild id='3' />
        <grandchild id='4' />
      </child>
    </root>";
            XDocument doc = XDocument.Parse(xml);
     
            foreach (XElement element in doc.Descendants("grandchild"))
            {
                Console.WriteLine(element);
            }
        }
    }
    

    Result:

    <grandchild id="3" />
    <grandchild id="4" />
    
    Answered on December 24, 2018.
    Add Comment

    Below codes indicates namespace:

    String TheDocumentContent =
    @"
    <TheNamespace:root xmlns:TheNamespace = 'http://www.w3.org/2001/XMLSchema' >
      <TheNamespace:GrandParent>
        <TheNamespace:Parent>
          <TheNamespace:Child theName = 'Fred' />
          <TheNamespace:Child theName = 'Gabi' />
          <TheNamespace:Child theName = 'George'/>
          <TheNamespace:Child theName = 'Grace' />
          <TheNamespace:Child theName = 'Sam' />
        </TheNamespace:Parent>
      </TheNamespace:GrandParent>
    </TheNamespace:root>
    ";
     
    XDocument TheDocument = XDocument.Parse( TheDocumentContent );
     
    //Example 1:
    var TheElements1 =
    from
      AnyElement
    in
      TheDocument.Descendants( "{http://www.w3.org/2001/XMLSchema}Child" )
    select
      AnyElement;
     
    ResultsTxt.AppendText( TheElements1.Count().ToString() );
     
    //Example 2:
    var TheElements2 =
    from
      AnyElement
    in
      TheDocument.Descendants( "{http://www.w3.org/2001/XMLSchema}Child" )
    where
      AnyElement.Attribute( "theName" ).Value.StartsWith( "G" )
    select
      AnyElement;
     
    foreach ( XElement CurrentElement in TheElements2 )
    {
      ResultsTxt.AppendText( "\r\n" + CurrentElement.Attribute( "theName" ).Value );
    }
    
    Answered on December 24, 2018.
    Add Comment

    Try this way:

    xml.Descendants().Where(p => p.Name.LocalName == "Name of the node to find")
    

         where xml is a XDocument.

    Be alert that the property Name returns an object that has a LocalName and a Namespace. So that is the reason to use Name.LocalName if we want to compare by name.

    Answered on December 24, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.