gpt4 book ai didi

C# 从另一个 XML 创建嵌套的 XML

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

我正在尝试将 XML 转换为具有元素属性的嵌套 XML。我在谷歌上搜索了很多,并在这里查看了一些问题和答案,但我仍然无法理解它。

我想使用 C#、linq to xml 将子节点分组到同一作者名下。

示例 XML:

<authors>
<author name="John">
<books>
<book type="Children">ABC</book>
</books>
<published> ---<new
<print year="2011"> ---<new
<publisher>Msoft</publisher> ---<new
</print> ---<new
</published> ---<new
</author>
<author name="May">
<books>
<book type="Children">A beautiful day</book>
</books>
<published> ---<new
<print year="2011"> ---<new
<publisher>hardsoft</publisher> ---<new
</print> ---<new
</published> ---<new
</author>
<author name="John">
<books>
<book type="Fiction">BBC</book>
</books>
<published> ---<new
<print year="2013"> ---<new
<publisher>dsney</publisher> ---<new
</print> ---<new
</published> ---<new
</author>
</authors>

期望输出:

<authors>
<author name="John">
<books>
<book type="Children">ABC</book>
<book type="Fiction">BBC</book>
</books>
<published>
<print year="2011">
<publisher>Msoft</publisher>
<publisher>hardsoft</publisher>
</print>
</published>
</author>
<author name="May">
<books>
<book type="Children">A beautiful day</book>
</books>
<published>
<print year="2013">
<publisher>dsney</publisher>
</print>
</published>
</author>
</authors>

如果有其他具有属性的节点需要在同一作者下分组,例如我应该添加另一个分组还是从上一个组中选择元素?

到目前为止,我已经尝试过:

XDocument doc = XDocument.Load(pathtoxmlfile);
var query = from e in doc.Elements("author")
group e by e.Attribute("name").Value into g
select new XElement("author", new XAttribute("name", g.Key),
new XElement("books",
g.Select(x => x.Element("books").Elements("book"))
, new XElement("published",
g.Select(y=>y.Elements("publisher")
)
)
)
);

XElement root = new XElement("authors", query);

它只输出 me inside 和 author 节点,没有入口。

<author>
<books>...this part is output as expect...
</books>
<published>
<publisher />
</published>
</author>

最佳答案

string xml = @"<authors>
<author name=""John"">
<books>
<book type=""Children"">ABC</book>
</books>
</author>
<author name=""May"">
<books>
<book type=""Children"">A beautiful day</book>
</books>
</author>
<author name=""John"">
<books>
<book type=""Fiction"">BBC</book>
</books>
</author>
</authors>";

XElement root = XElement.Parse(xml);
var query = from e in root.Elements("author")
group e by e.Attribute("name").Value into g
select new XElement("author", new XAttribute("name", g.Key),
new XElement("books",
g.Select(x => x.Element("books").Elements("book")).ToArray()));

XElement newRoot = new XElement("authors", query.ToArray());
Console.WriteLine(newRoot);

关于C# 从另一个 XML 创建嵌套的 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31318087/

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