【问题标题】:How to order the XML element using the child node?如何使用子节点对 XML 元素进行排序?
【发布时间】:2016-08-16 13:05:38
【问题描述】:

我想根据内部属性“Top”的值对 XML 元素进行升序排序。

<?xml version="1.0" encoding="utf-8"?>
    <Root>
      <Designer>
        <Sequence>
          <Left>603.875</Left>
          <Top>312.665</Top>
          <total>NaN</total>
          <Width>58.5</Width>
          <Height>45.5</Height>
          <ID>635b1aed-6ee3-4cf5-9324-b0246f3a0c1d</ID>
          <zIndex>0</zIndex>
          <IsGroup>false</IsGroup>
          <ParentID>00000000-0000-0000-0000-000000000000</ParentID>    
          <ItemLabel>123</ItemLabel>
        </Sequence>
        <Sequence>
          <Left>568.875</Left>
          <Top>29.664999999999992</Top>
          <total>NaN</total>
          <Width>58.5</Width>
          <Height>45.5</Height>
          <ID>9dd9a96d-4356-49c6-85a3-6b898983e688</ID>
          <zIndex>1</zIndex>
          <IsGroup>false</IsGroup>
          <ParentID>00000000-0000-0000-0000-000000000000</ParentID>
          <ItemLabel>321</ItemLabel>
        </Sequence>
      </Designer>
<Parameters>
<Value> 
<Name> Label 1 </Name>
<ID> 1 </ID>
</Value>
<Value> 
<Name> Label 2 </Name>
<ID> 2 </ID>
</Value>
</Parameters>

</Root>

这是我尝试过的代码。

   try
   {
         XElement root = XElement.Load(MainWindow.Container.globalfilename +".xml");
         var orderedtabs = root.Elements("Designer").Elements("Sequence")
                                      .OrderBy(xtab => (float)xtab.Element("Top"))
                                      .ToArray();

         foreach (XElement tab in orderedtabs)
         {
                    root.Add(tab);
         }
         root.Save("xmlfile" + ".xml");
         MessageBox.Show("Sorted");
   }

当我尝试创建一个新的 XML 文件时,标签被删除了。但我可以从 . 但是,它的元素被删除了。

请在我出错的地方提供答案或更正。

提前谢谢你。

【问题讨论】:

  • 我会做一个GroupBy(x =&gt; x.Element("Top").Value).OrderBy()....
  • 您的代码的确切问题是什么?运行时会发生什么?
  • @theFunkyEngineer 在编写时, 标签被删除,其他标签如 也被删除。

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


【解决方案1】:

您的 Root、Designer 和 Parameters 标记将被删除,因为您只选择了随后添加到根顶部的 Sequences 标记。建议把Designer下面的所有Sequences标签都去掉,重新在Designer下重新插入有序的Sequences:

        XElement root = XElement.Load("input.xml");
        // Extract Sequences ordered by 'Top'
        var orderedtabs = root.Elements("Designer").Elements("Sequence")
                              .OrderBy(xtab => (float)xtab.Element("Top"))
                              .ToArray();
        // Remove Sequences from xml
        root.Descendants("Designer").Elements("Sequence").Remove();
        // Reinsert Sequences in new order under the Designer element
        XElement designer = root.Descendants("Designer").FirstOrDefault();
        foreach (XElement tab in orderedtabs)
        {
            designer.Add(tab);
        }
        root.Save("xmlfile" + ".xml");

【讨论】:

    猜你喜欢
    • 2010-10-09
    • 1970-01-01
    • 2023-02-01
    • 2021-11-12
    • 2020-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多