Retrieve list of xml tag of child nodes in linQ to xml

370 Views Asked by At

I'm trying to get all the list of the different child nodes (not starting from root) of a loaded XML into a list of strings, I had done using System.Xml library but I want to write the same code with LINQ to XML too. I had found a code that helped me a lot but it starts from Root, here is the code:

List<string> nodesNames = new List<string>();
XDocument xdoc1 = XDocument.Load(destinationPath);
XElement root = xdoc1.Document.Root;

foreach (var name in root.DescendantNodes().OfType<XElement>()
        .Select(x => x.Name).Distinct())
{
        if (!nodesNames.Contains(name.ToString()))
        nodesNames.Add(name.ToString());
}

With this, I get the list of all child nodes + the parent node too, which I don't want to use.FirstChild or to delete manually from the list because I want a TOTALLY dynamic code and I have in input the parent node passed by the user.

For a better comprehension, this is the code that working for me but with System.Xml:

List<string> nodesNames = new List<string>();
XmlDocument doc = new XmlDocument();
doc.Load(destinationPath);
XmlNodeList elemList = doc.GetElementsByTagName(inputParentNode);

for (int i = 0; i < elemList.Count; i++)
{
        XmlNodeList cnList = (elemList[i].ChildNodes);
        for (int j = 0; j < cnList.Count; j++)
        {
                string name = cnList[j].Name;
                if (!nodesNames.Contains(name))
                        nodesNames.Add(name);
        }
}

And this is an easy sample of the XML:

<?xml version='1.0' encoding='UTF-8'?>
<parentlist>
        <parent>
                <firstchild>someValue</firstchild>
                <secondchild>someValue</secondchild>
        </parent>
        <parent>
                <firstchild>someValue</firstchild>
                <secondchild>someValue</secondchild>
                <thirdchild>someValue</thirdchild>
        </parent>
</parentlist>

To resume:

  • in the first case i obtain nodesNames = ["parent", "firstchild", "secondchild", "thirdchild"]
  • in the second case i obtain nodesNames = ["firstchild", "secondchild", "thirdchild"]

I just want to fix the first to obtain the same result as the second.

1

There are 1 best solutions below

3
jdweng On

Try following :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication2
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
           XDocument doc = XDocument.Load(FILENAME);
           XElement parentlist= doc.Root;
           List<string> descendents = parentlist.Descendants().Where(x => x.HasElements).Select(x => string.Join(",", x.Name.LocalName, string.Join(",", x.Elements().Select(y => y.Name.LocalName)))).ToList();


        }
    }
}