views:

90

answers:

1

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.

+5  A: 
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);
}
Rex M
Thanks a lot! Having never parsed xml before, your explanation helped tremendously. Cheers
yc23