[英]C#: Sort xml nodes and childnodes using attribute value
Referencing the two questions here and here参考这里和这里的两个问题
I would like to sort on child nodes as well, but resetting for each "outer" node.我也想对子节点进行排序,但要为每个“外部”节点重置。
So:所以:
<Root>
<I aa="1">
<s aa="3"/>
<s aa="1"/>
<s aa="2"/>
</I>
<I aa="5">
<s aa="3"/>
<s aa="1"/>
<s aa="2"/>
</I>
<I aa="3">
<s aa="3"/>
<s aa="1"/>
<s aa="2"/>
</I>
<I aa="4">
<s aa="3"/>
<s aa="1"/>
<s aa="2"/>
</I>
</Root>
Would become:会成为:
<Root>
<I aa="1">
<s aa="1"/>
<s aa="2"/>
<s aa="3"/>
</I>
<I aa="3">
<s aa="1"/>
<s aa="2"/>
<s aa="3"/>
</I>
<I aa="4">
<s aa="1"/>
<s aa="2"/>
<s aa="3"/>
</I>
<I aa="5">
<s aa="1"/>
<s aa="2"/>
<s aa="3"/>
</I>
</Root>
I tried different variations of the XDocument sorting, but I cannot get the syntax right.我尝试了 XDocument 排序的不同变体,但语法不正确。
Hoping someone can help, or provide me with an idea.希望有人能提供帮助,或者给我一个想法。
You need some recursion here - each element needs to be cloned and its child elements sorted by the aa
attribute.您在这里需要一些递归——每个元素都需要被克隆,其子元素按
aa
属性排序。 A method to do that might look like this:这样做的方法可能如下所示:
private static XElement CopyAndSort(XElement e)
{
var elements = e.Elements()
.OrderBy(x => (string)x.Attribute("aa"))
.Select(CopyAndSort);
return new XElement(e.Name, e.Attributes(), elements);
}
If you then call that with your Root
element, you will get back a new Root
element with all its children sorted (and their children sorted, and so on).如果您随后使用
Root
元素调用它,您将得到一个新的Root
元素,其所有子元素都已排序(以及它们的子元素已排序,等等)。
See this fiddle for a working demo.有关工作演示,请参阅此小提琴。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.