gpt4 book ai didi

c# - 对相同命名的 xml 节点求和

转载 作者:太空宇宙 更新时间:2023-11-03 15:19:58 24 4
gpt4 key购买 nike

我编辑了这个 MSDN 小例子 https://support.microsoft.com/en-us/kb/311530

我有以下 2 个 XML

Book1.xml

<?xml version="1.0"?>
<catalog>
<book1 id="1" />
<bookSum number="1" />
</catalog>

Book2.xml

<?xml version="1.0"?>
<catalog>
<book2 id="2" />
<bookSum number="1" specialAttribute="123" />
</catalog>

C#代码

XmlReader xmlreader1 = XmlReader.Create(@"C:\Book1.xml");
XmlReader xmlreader2 = XmlReader.Create(@"C:\book2.xml");

DataSet ds = new DataSet();
ds.ReadXml(xmlreader1);
DataSet ds2 = new DataSet();
ds2.ReadXml(xmlreader2);
ds.Merge(ds2);
ds.WriteXml(@"C:\Merge.xml");
Console.WriteLine("Completed merging XML documents");

Merge.xml (Book1.xml + Book2.xml)

<?xml version="1.0" standalone="yes"?>
<catalog>
<book1 id="1" />
<bookSum number="1" />
<bookSum number="1" specialAttribute="x" />
<book2 id="2" />
</catalog>

问题是

如何加入

<bookSum number="1" />
<bookSum number="1" specialAttribute="123" />

成一行?

<bookSum number="2" specialAttribute="123" />

最佳答案

我是这样做的并且正在工作:

var doc = XDocument.Load(@"C:\Book1.xml");
doc.Root.Add(XDocument.Load(@"C:\Book2.xml").Root.Elements()); // merged

var sum = doc.Descendants("bookSum").Attributes("number").Sum(t => int.Parse(t.Value));

var xElement = new XElement("bookSum", new XAttribute("number", sum));
foreach(var attrib in doc.Descendants("bookSum").Attributes())
{
if (xElement.Attribute(attrib.Name) == null)
xElement.Add(attrib);
}

doc.Descendants("bookSum").ToList().ForEach(t => t.ReplaceWith(xElement));
doc.Root.Descendants("bookSum").First().Remove();
Console.WriteLine(doc);

关于c# - 对相同命名的 xml 节点求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37704536/

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