6

我需要从 XML 中对“文档”值进行分组。问题是因为键值(productType)可以是多个。

这是 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>

这就是我尝试的:

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

仅当存在一个 productType 元素时,我的代码才有效。如果 productType 有多个值,如何更改我的代码工作?

4

1 回答 1

2

您没有解释您想要什么结果,但我怀疑您想要以下分组:

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

输入为

<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>

输出

Group x1 has the following members:
        title1
        title2

Group x3 has the following members:
        title1
        title3

Group x2 has the following members:
        title4
于 2012-05-26T12:47:59.320 回答