【发布时间】:2015-07-10 16:25:45
【问题描述】:
我正在尝试将 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);
它只在内部和作者节点输出我,没有条目。
<author>
<books>...this part is output as expect...
</books>
<published>
<publisher />
</published>
</author>
【问题讨论】:
-
看起来您实际上并没有尝试转换某些内容。我在您的问题中只看到输入数据和预期结果 - 并且看不到您的任何尝试。到目前为止有什么努力吗?你遇到过什么问题?
-
您是否考虑过使用 Xsl 转换来解决这个问题?如果你的输出也是 Xml 并且你不需要对数据进行复杂的处理,这应该比使用 Linq 更容易。
-
你可以看看stackoverflow.com/questions/5603284/linq-to-xml-groupby。看起来与您尝试做的非常相似。
-
@Andy Korneyev - 抱歉,我很着急,没有发布我已经尝试过的代码。以前我将“ var query = from author in root.Root.Elements("author") group author by author.Attribute("name") 编码为 groupedAuthor select groupedAuthor; 在 VS 中尝试了此代码,但只给了我一个错误。跨度>
标签: c# xml linq-to-xml