Ben
Ben

Reputation: 211

Get Just 3rd level XML nodes' names LINQ C#

I'm trying to get the 3rd level names from a XML. I found this but it gives me also the 4th level, which i don't want. How should i do it?

XDocument xdoc = XDocument.Load(path + @"\Pages\Results\Target_XML.xml");

            foreach (var name in xdoc.Root.Element("Veg").DescendantNodesAndSelf().OfType<XElement>().Select(x => x.Name).Distinct())
            {
                Console.WriteLine(name);
            }

Example (I want just the Tom and Car as strings, without Name and Cal) - This is the XML:

    <DEV>
        <Veg>
             <Tom>
                  <Name>aa</Name>
                  <Cal>99</Cal>
             </Tom>
             <Car>
                  <Name>aa</Name>
                  <Cal>99</Cal>
             </Car>
        </Veg>

        <Fru>
             <Ban>
                  <Name>aa</Name>
                  <Cal>99</Cal>
             </Ban>
        </Fru>  
    </DEV>

Upvotes: 0

Views: 578

Answers (3)

var l_RootElement = XElement.Load(path + @"\Pages\Results\Target_XML.xml");
foreach (var l_VegElement in l_RootElement.Elements("Veg").Elements()) {
    Console.WriteLine(l_VegElement.Name);
}

Upvotes: 0

cosh
cosh

Reputation: 480

You can reference the child nodes with XElement's ChildNodes property. Like this:

XmlNodeList childNodes = xdoc.Root.Element("Veg").ChildNodes;

In this case, the childNodes list would contain the 3rd level nodes you want.

Upvotes: 0

jdweng
jdweng

Reputation: 34419

Using xml linq :

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

using System.Runtime.InteropServices;

namespace ConsoleApplication23
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            List<string> strings = doc.Elements().Elements().Elements().Select(x => x.Name.LocalName).ToList();



        }
    }

}

Upvotes: 1

Related Questions