You have not explained what result you want, but I suspect you want the following grouping:
var documentGroups = from document in XDocument.Load("input.xml").Descendants("Document") from productType in document.Element("productTypes").Elements("productType") group document by (string)productType.Attribute("id"); foreach (var documentGroup in documentGroups) { Console.WriteLine("Group {0} has the following members:", documentGroup.Key); foreach (XElement document in documentGroup) { Console.WriteLine("\t{0}", (string)document.Element("title")); } Console.WriteLine(); }
When entering
<Documents> <Document> <id>1</id> <title>title1</title> <productTypes> <productType id="x1">Capital Costs Analysis Forum - Brazil</productType> <productType id="x3">Environmental, Health and Safety & Sustainability</productType> </productTypes> </Document> <Document> <id>2</id> <title>title2</title> <productTypes> <productType id="x1">Capital Costs Analysis Forum - Brazil</productType> </productTypes> </Document> <Document> <id>3</id> <title>title3</title> <productTypes> <productType id="x3">Environmental, Health and Safety & Sustainability</productType> </productTypes> </Document> <Document> <id>4</id> <title>title4</title> <productTypes> <productType id="x2">Defense, Risk & Security</productType> </productTypes> </Document> </Documents>
which outputs
Group x1 has the following members: title1 title2 Group x3 has the following members: title1 title3 Group x2 has the following members: title4
source share