我想知道是否有人可以在以下方面提供帮助:
我有一个这样的 xml 文档:
<div class="_cl">element description 1</div>
<div class="_cl">
<anotherele>dtls</anotherele>
<anotherele>moredtls</anotherele>
</div>
<div class="_cl">
<anotherele>dtls</anotherele>
<anotherele>moredtls</anotherele>
</div>
<div class="_cl">element description 2</div>
<div class="_cl">
<anotherele>dtls</anotherele>
<anotherele>moredtls</anotherele>
</div>
<div class="_cl">
<anotherele>dtls</anotherele>
<anotherele>moredtls</anotherele>
</div>
我想知道 linq 中是否有任何方法可以按没有子元素的元素对其进行分组。基本上,尝试以某种方式构建文档:
<div class="_cl">element description 1
<div class="_cl">
<anotherele>dtls</anotherele>
<anotherele>moredtls</anotherele>
</div>
<div class="_cl">
<anotherele>dtls</anotherele>
<anotherele>moredtls</anotherele>
</div>
</div>
<div class="_cl">element description 2
<div class="_cl">
<anotherele>dtls</anotherele>
<anotherele>moredtls</anotherele>
</div>
<div class="_cl">
<anotherele>dtls</anotherele>
<anotherele>moredtls</anotherele>
</div>
</div>
我第一次糟糕的尝试是这样的:
var n = from a in doc.Descendants()
where a.Name.LocalName == "div" && (string)a.Attribute("class") == "_cl"
group a by a.Value.Length<50 into g
select new { k = g.Key, p = g.Count() };
希望这是有道理的,并提前致谢。
斯图
最佳答案
这里是一个例子,假设输入是
<body>
<div class="_cl">element description 1</div>
<div class="_cl">
<anotherele>dtls</anotherele>
<anotherele>moredtls</anotherele>
</div>
<div class="_cl">
<anotherele>dtls</anotherele>
<anotherele>moredtls</anotherele>
</div>
<div class="_cl">element description 2</div>
<div class="_cl">
<anotherele>dtls</anotherele>
<anotherele>moredtls</anotherele>
</div>
<div class="_cl">
<anotherele>dtls</anotherele>
<anotherele>moredtls</anotherele>
</div>
</body>
然后是代码
XDocument input = XDocument.Load("input.xml");
XDocument output = new XDocument(
new XElement(input.Root.Name,
from el in input.Root.Elements()
where el.Elements().Any()
group el by el.NodesBeforeSelf().OfType<XElement>().LastOrDefault(e => !e.Elements().Any()) into g
select new XElement(g.Key.Name,
g.Key.Attributes(),
g.Key.Nodes(),
g)
));
output.Save(Console.Out);
输出
<body>
<div class="_cl">element description 1<div class="_cl"><anotherele>dtls</anoth
erele><anotherele>moredtls</anotherele></div><div class="_cl"><anotherele>dtls</anotherele><anotherele>moredtls</anotherele></div></div>
<div class="_cl">element description 2<div class="_cl"><anotherele>dtls</anoth
erele><anotherele>moredtls</anotherele></div><div class="_cl"><anotherele>dtls</anotherele><anotherele>moredtls</anotherele></div></div>
</body>
我想这就是您想要的,除了缩进。至于缩进,您可以通过使用 XDocument.Load("input.xml", LoadOptions.PreserveWhitespace)
加载输入来更接近您想要的结果。
有关此分组方法的更多信息,请参阅 http://msmvps.com/blogs/martin_honnen/archive/2009/11/27/grouping-with-linq-to-xml.aspx .
关于c# - Linq-to-xml 按没有子元素的元素分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8169885/