gpt4 book ai didi

c# - 使用 XDocument 更改 XML 的顺序

转载 作者:太空狗 更新时间:2023-10-29 20:22:41 26 4
gpt4 key购买 nike

我想使用 XDocument 更改 XML 的顺序

<root>
<one>1</one>
<two>2</two>
</root>

我想更改顺序,使 2 出现在 1 之前。此功能是内置的还是我必须自己做。例如,然后删除 AddBeforeSelf()?

谢谢

最佳答案

与上面类似,但将其包装在扩展方法中。在我的例子中,这对我来说很好,因为我只想确保在用户保存 xml 之前在我的文档中应用特定的元素顺序。

public static class XElementExtensions
{
public static void OrderElements(this XElement parent, params string[] orderedLocalNames)
{
List<string> order = new List<string>(orderedLocalNames);
var orderedNodes = parent.Elements().OrderBy(e => order.IndexOf(e.Name.LocalName) >= 0? order.IndexOf(e.Name.LocalName): Int32.MaxValue);
parent.ReplaceNodes(orderedNodes);
}
}
// using the extension method before persisting xml
this.Root.Element("parentNode").OrderElements("one", "two", "three", "four");

关于c# - 使用 XDocument 更改 XML 的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/224253/

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