gpt4 book ai didi

c# - 如何按多个值对 XML 数据进行分组

转载 作者:数据小太阳 更新时间:2023-10-29 01:52:08 26 4
gpt4 key购买 nike

我需要对 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 有多个值,如何更改我的代码以使其正常工作?

最佳答案

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

        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

关于c# - 如何按多个值对 XML 数据进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10766128/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com