Link to home
Start Free TrialLog in
Avatar of mdeek
mdeek

asked on

How to query nested XML Elements with Linq

I have an XML File that follows similar structure (it is the API of of one of our vendors that returns this file) - it comes in looking like:

<folder name="something">
   <folder name="nice">
       <file name="cool" />
       <file name="jack" />
   </folder>
   <folder name="steve">
          <folders or files might go there>
   </folder>
</folder>

What id like to do is easily be able to get ALL of the files, and I can do that easily enough but I need to know the paths fo the files, like root/cool/filename or root/james/filename


<folder name="something">
   <folder name="nice">
       <file name="cool" />
       <file name="jack" />
   </folder>
   <folder name="steve">
          <folders or files might go there>
   </folder>
</folder>

Open in new window

Avatar of Craig Wagner
Craig Wagner
Flag of United States of America image

Do you have to use LINQ? I used the following file contents:

<folder name="something">
    <folder name="nice">
        <file name="cool" />
        <file name="jack" />
    </folder>
    <folder name="steve">
        <folder name="boo">
            <file name="hoo" />
        </folder>
    </folder>
</folder>

Along with the code snippet below to produce this output:

cool/nice/something/
jack/nice/something/
hoo/boo/steve/something/

Yes, the results are backwards, you'd have to build the string in the reverse order, but it gives you the general idea.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load( "XMLFile1.xml" );
 
XmlNodeList nodeList = xmlDoc.SelectNodes( "//file" );
 
foreach( XmlNode node in nodeList )
{
    XmlNode tempNode = node;
 
    do
    {
        if( tempNode.Attributes != null && tempNode.Attributes["name"] != null )
        {
            Console.Write( tempNode.Attributes["name"].Value + "/" );
        }
 
        tempNode = tempNode.ParentNode;
    } while( tempNode != null );
 
    Console.WriteLine();
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of jinal
jinal
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial