简体   繁体   中英

Get Nodes from XML having same parent and child name

    <maintag>
           <CENTER>
              <ID>11</ID>
              <CENTER>333</CENTER>
           </CENTER>
           <PRODUCTID>100</PRODUCTID>
           <LastNum>0900</LastNum>

    </maintag>

I have above XML where there is same tag name for parent and one of its child node ie CENTER. I know i can parse it in multiple steps going at index 0 of main tag , then index 0 of CENTER tag will give ID and Index 1 of center tag will give value 333 of CENTER etc. But is there a way where i can directly get values of both the ID and CENTER (11 , 333 ) directly.

class Program
  {
    static void Main(string[] args)
    {
      string xml = @"<maintag>
           <CENTER>
              <ID>11</ID>
              <CENTER>333</CENTER>
           </CENTER>
           <PRODUCTID>100</PRODUCTID>
           <LastNum>0900</LastNum>
    </maintag>";

      XmlDocument xd = new XmlDocument();
      xd.LoadXml(xml);

      string center = xd.DocumentElement.SelectSingleNode("CENTER/CENTER").InnerText;
      string id = xd.DocumentElement.SelectSingleNode("CENTER/ID").InnerText;


    }

I'm giving you a very general answer here:

 var elementsWithChildrenOfSameName = 
    xmlDoc.Root.Elements()
     .Where(ele => ele.Elements().Any(t => t.Name == ele.Name)).ToList();

From there you can easily get the data you want.

Or in a integrated query style:

 var elementsWithChildrenOfSameName = 
        from parent in xmlDoc.Root.Elements()
        from child in parent.Elements()
        where child.Name == parent.Name
        select parent; // Or maybe select the id's?

LinqToXml XDocument query:

XDocument doc = XDocument.Parse(x);
var res = doc.Descendants("CENTER")
             .Where(el => el.Elements("ID").Count() > 0 && el.Elements("CENTER").Count() > 0)
             .Select(el => new { 
                                 id = el.Element("ID").Value,
                                 center = el.Element("CENTER").Value 
                               })
             .ToList();

Select all CENTER tags, which have in children both ID and CENTER tags and take their ID and CENTER values into the new result collection.

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