【问题标题】:How to sort nested nodes xml [duplicate]如何对嵌套节点xml进行排序[重复]
【发布时间】:2014-11-24 19:49:08
【问题描述】:

我在下面提到了 xml。

    <?xml version="1.0" encoding="UTF-8"?>
<insiders>
   <insider>
      <linkages>
         <linkage>
            <owner id="112025">
               <namestrings>
                  <namestring />
               </namestrings>
            </owner>
            <relationshipHistory>
               <relationship code="201" />
            </relationshipHistory>
         </linkage>
      </linkages>
   </insider>
   <insider>
      <linkages>
         <linkage>
            <owner id="100354">
               <namestrings>
                  <namestring>KAITUE RAIMO KUOLINPESÄ</namestring>
               </namestrings>
            </owner>
            <relationshipHistory>
               <relationship code="302">
                  <from>1998-10-23</from>
               </relationship>
            </relationshipHistory>
         </linkage>
         <linkage>
            <owner id="126799">
               <namestrings>
                  <namestring />
               </namestrings>
            </owner>
            <relationshipHistory>
               <relationship code="204">
                  <from>2014-09-09</from>
               </relationship>
               <relationship code="201">
                  <to>2014-09-08</to>
               </relationship>
            </relationshipHistory>
         </linkage>
      </linkages>
   </insider>
</insiders>

我想根据code 属性对relationshipHistory 节点进行排序,在提到的xml 中code=201 元素应该首先然后code=204 之后。 谁能帮帮我,我该怎么做?

【问题讨论】:

  • 期望的输出是什么? XML 或类型的集合等?

标签: c# xml


【解决方案1】:

我会这样做:

我假设您可以选择“relationshipHistory”元素,所以我只显示排序。

class Program
{
    static void Main(string[] args)
    {
        XDocument xdoc = XDocument.Parse(xml);
        XElement history = xdoc.Element("relationshipHistory");
        IEnumerable<XElement> histories = history.Elements();
        // Sort elements and create new elements because the RemoveAll method will delete the old ones.
        IEnumerable<XElement> historiesSorted = 
            histories
            .OrderBy(x => int.Parse(x.Attribute("code").Value))
            .Select(x => new XElement(x))
            .ToList();
        // Remove the old elements.
        history.RemoveAll();
        // Add the sorted elements to the parent element.
        foreach (var item in historiesSorted)
        {
            history.Add(item);
        }
    }

    static string xml = @"<?xml version='1.0' encoding='UTF-8\'?>
        <relationshipHistory>
            <relationship code='204'>
                <from>2014-09-09</from>
            </relationship>
            <relationship code='201'>
                <to>2014-09-08</to>
            </relationship>
        </relationshipHistory>";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多