使用LINQ扁平化XML文件的简单方法 [英] Easy way to flatten XML file with LINQ
问题描述
LINQ是否有一种简单的方法来展平XML文件?
Is there an easy way with LINQ to flatten an XML file?
我可以用XSLT看到很多方法,但是想知道LINQ的最佳选择是什么?
I can see a number of ways with XSLT but wondered what the best option with LINQ would be?
我不能完全按照stackoverflow似乎过滤人字形字符的方式来放置xml结构.但是它是这样的
I cant put the xml structure up exactly as stackoverflow seems to filter chevron chars. But its something like this
nodeA
-nodeA1
-nodeA2
NodeB
我想结束
nodeA
nodeA1
nodeA2
NodeB
推荐答案
确定;它取决于您想要的输出-使用XElement,您需要做一些工作以删除所有后代节点等.但是,使用XmlDocument实际上非常简单:
OK; it depends on the output you want - with XElement you'd need to do a bit of work to remove all the descendent nodes etc. However, it is actually quite simple with XmlDocument:
string xml = @"<xml><nodeA><nodeA1/><nodeA2/></nodeA><NodeB/></xml>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlDocument clone = new XmlDocument();
XmlElement root = (XmlElement) clone.AppendChild(clone.CreateElement("xml"));
foreach(XmlElement el in doc.SelectNodes("//*")) {
root.AppendChild(clone.ImportNode(el, false));
}
Console.WriteLine(clone.OuterXml);
输出:
<xml><xml /><nodeA /><nodeA1 /><nodeA2 /><NodeB /></xml>
[是] 在这种情况下要定义展平"吗?即之前"和之后"? XDocument具有Descendants()和DescendantNodes()可以完成此任务...
[was] Care to define "flatten" in this context? i.e. "before" and "after"? XDocument has Descendants() and DescendantNodes() which might do the job...
这篇关于使用LINQ扁平化XML文件的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!