简体   繁体   中英

trouble parsing deeply nested attributes using LINQ to XML

I have been trying to parse this xml in c#

<schema uri=http://blah.com/schema >
   <itemGroups>
     <itemGroup description="itemGroup1 label="itemGroup1">
       <items>
        <item description="The best" itemId="1" label="Nutella"/>
        <item description="The worst" itemId="2" label="Vegemite"/>
       </items>
     </itemGroup>
   </itemGroups>
</schema>

\itemGroup1\Nutella-The best
\itemGroup1\Vegemite-The worst

Any help or direction would be appreciated.

XDocument xDoc = XDocument.Load(myXml); //load your XML from file or stream

var rows = xDoc.Descendants("item").Select(x => string.Format(
                    @"\{0}-{1}\{2}-{3}",
                    x.Ancestors("itemGroup").First().Attribute("description").Value,
                    x.Ancestors("itemGroup").First().Attribute("label").Value,
                    x.Attribute("label").Value,
                    x.Attribute("description").Value));

Let's break down what we're doing:

  • xDoc.Descendants("item") gets us all <item> elements in the entire document

  • Select(x => string.Format(format, args) projects each <item> we got from the last operation into whatever format we specify in the lambda. In this case, a formatted string .

  • In terms of the XML tree, we're "sitting at" the <item> level, so we need to roll back up the tree to get the data for the parent group using Ancestors . Since that method returns a sequence of elements, we know we want the first (nearest to us) so we can read its attribute.

Now you have an IEnumerable<string> , one for each <item> in your XML document and the information in the format you specified:

foreach(string row in rows)
{
    Console.WriteLine(row);
}

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