开发者

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜