How to group XML data by multiple values

I need to group the value of "Document" from XML. The problem is that the key value (productType) can be a multiple.

This is XML:

<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 &amp; 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 &amp; Sustainability</productType> </productTypes> </Document> <Document> <id>4</id> <title>title4</title> <productTypes> <productType id="x2">Defense, Risk &amp; Security</productType> </productTypes> </Document> 

And here is what I am trying:

 var documents = from document in some.Descendants("Document") group document by (string)document .Element("productTypes") .Elements("productType") .First() into docGroup select docGroup; 

My code only works if there is one productType element. How to change my code to work if there are multiple productType values?

+6
source share
1 answer

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 &amp; 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 &amp; Sustainability</productType> </productTypes> </Document> <Document> <id>4</id> <title>title4</title> <productTypes> <productType id="x2">Defense, Risk &amp; 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 
+2
source

Source: https://habr.com/ru/post/916740/


All Articles