如何对嵌套节点进行排序 xml
本文关键字:排序 xml 节点 嵌套 | 更新日期: 2023-09-27 18:31:53
我在下面有 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
然后。任何人都可以帮我该怎么做吗?
这就是我会这样做的:
我假设您可以选择"关系历史记录"元素,所以我只显示排序。
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>";
}