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