简体   繁体   中英

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>

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();



        }
    }

}

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM