我想使用 XDocument 更改 XML 的顺序
<root>
<one>1</one>
<two>2</two>
</root>
我想更改顺序,以便 2 出现在 1 之前。这个功能是内置的还是我必须自己做。例如,删除然后 AddBeforeSelf()?
谢谢
我想使用 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");
试试这个解决方案...
XElement node = ...get the element...
//Move up
if (node.PreviousNode != null) {
node.PreviousNode.AddBeforeSelf(node);
node.Remove();
}
//Move down
if (node.NextNode != null) {
node.NextNode.AddAfterSelf(node);
node.Remove();
}
这应该可以解决问题。它根据内容对根的子节点进行排序,然后更改它们在文档中的顺序。这可能不是最有效的方法,但根据您希望使用 LINQ 看到的标签来判断。
static void Main(string[] args)
{
XDocument doc = new XDocument(
new XElement("root",
new XElement("one", 1),
new XElement("two", 2)
));
var results = from XElement el in doc.Element("root").Descendants()
orderby el.Value descending
select el;
foreach (var item in results)
Console.WriteLine(item);
doc.Root.ReplaceAll( results.ToArray());
Console.WriteLine(doc);
Console.ReadKey();
}
除了编写 C# 代码来实现这一点之外,您还可以使用 XSLT 来转换 XML。