我想使用 LINQ 通过在“Summary”字段上执行 GROUPBY 并对 Balance 字段求和来将输入 XML 转换为输出 XML。
输入 XML:
<Root>
<Account>
<Summary>Checking</Summary>
<Comprehensive>Interest Checking Account</Comprehensive>
<Currency>Dollar</Currency>
<Balance>10000000.000000</Balance>
</Account>
<Account>
<Summary>Savings</Summary>
<Comprehensive>Market Account</Comprehensive>
<Currency>Dollar</Currency>
<Balance>20000000.000000</Balance>
</Account>
<Account>
<Summary>Checking</Summary>
<Comprehensive>Interest Checking Account</Comprehensive>
<Currency>Dollar</Currency>
<Balance>50000000.000000</Balance>
</Account>
</Root>
输出 XML:
<Root>
<Account>
<Summary>Checking</Summary>
<Comprehensive>Interest Checking Account</Comprehensive>
<Currency>Dollar</Currency>
<Balance>60000000.000000</Balance>
</Account>
<Account>
<Summary>Savings</Summary>
<Comprehensive>Market Account</Comprehensive>
<Currency>Dollar</Currency>
<Balance>20000000.000000</Balance>
</Account>
</Root>
我尝试了这个但无法获取节点/元素:
XElement groupData = new XElement("Root",
chartData.Elements().GroupBy(x => x.Element("Summary").Value).
Select(g => new XElement("Account", g.Key, g.Elements("Comprehensive"),
g.Elements("Currency"),
g.Sum(
s =>
(decimal)
s.Element("Balance")))));
任何帮助,将不胜感激。提前致谢。
如果您不需要中间对象,您可以使用
XDocument input = XDocument.Load("input.xml");
XDocument output =
new XDocument(
new XElement(input.Root.Name,
from account in input.Root.Elements("Account")
group account by account.Element("Summary").Value into g
select new XElement("Account",
g.ElementAt(0).Elements().Where(e => e.Name != "Balance"),
new XElement("Balance", g.Elements("Balance").Sum(b => (decimal)b)
))));
output.Save("output.xml");
或者使用方法语法,您可以使用
XDocument input = XDocument.Load(@"input.xml");
XDocument output = new XDocument(
new XElement(input.Root.Name,
input.Root.Elements("Account")
.GroupBy(a => a.Element("Summary").Value)
.Select(g => new XElement("Account",
g.ElementAt(0).Elements().Where(e => e.Name != "Balance"),
new XElement("Balance", g.Elements("Balance").Sum(b => (decimal)b)
)))));
output.Save("output.xml");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)