【问题标题】:Change order of XML using XDocument使用 XDocument 更改 XML 的顺序
【发布时间】:2008-10-22 02:19:31
【问题描述】:

我想使用 XDocument 更改 XML 的顺序

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

我想更改顺序,以便 2 出现在 1 之前。这个功能是内置的还是我必须自己做。比如去掉然后AddBeforeSelf()?

谢谢

【问题讨论】:

    标签: c# .net linq linq-to-xml


    【解决方案1】:

    与上面类似,但将其包装在扩展方法中。在我的情况下,这对我来说很好,因为我只想确保在用户保存 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");
    

    【讨论】:

      【解决方案2】:

      试试这个解决方案...

      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();
      }
      

      【讨论】:

        【解决方案3】:

        这应该可以解决问题。它根据内容对根的子节点进行排序,然后更改它们在文档中的顺序。这可能不是最有效的方法,但根据您希望使用 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();
        }
        

        【讨论】:

          【解决方案4】:

          除了编写 C# 代码来实现这一点之外,您还可以使用 XSLT 来转换 XML。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-09-21
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-02-14
            • 2012-12-07
            相关资源
            最近更新 更多