根据孙级对 XDocument 的元素进行排序
本文关键字:元素 排序 XDocument 孙级 | 更新日期: 2023-09-27 18:30:19
我将以下XML(以缩写形式显示)加载到XDocument对象中。
<employees>
<employee>
<identification>
<firstName>John</firstName>
<lastName>Smith</lastName>
</identification>
<payment contractType="1">
<income type="4" startDate="2014-10-01" endDate="2014-10-31">
</income>
</payment>
</employee>
<employee>
<identification>
<firstName>John</firstName>
<lastName>Balmer</lastName>
</identification>
<payment contractType="2">
<income type="2" startDate="2014-10-01" endDate="2014-10-31">
</income>
</payment>
</employee>
</employees>
我想在我的 XDocument 对象上应用一个 linq 查询,该查询根据<lastname>
对所有节点进行排序,然后使用 Linq to XML <firstname>
。因此,在应用 linq 之后,我的 XDocument 对象将包含以下 XML:
<employees>
<employee>
<identification>
<firstName>John</firstName>
<lastName>Balmer</lastName>
</identification>
<payment contractType="2">
<income type="2" startDate="2014-10-01" endDate="2014-10-31">
</income>
</payment>
</employee>
<employee>
<identification>
<firstName>John</firstName>
<lastName>Smith</lastName>
</identification>
<payment contractType="1">
<income type="4" startDate="2014-10-01" endDate="2014-10-31">
</income>
</payment>
</employee>
</employees>
// Extract "employee" Xelements in order.
var orderedEmployees =
from employee in xml.Descendants("employee")
orderby employee.Element("identification").Element("lastName").Value,
employee.Element("identification").Element("firstName").Value
select employee;
// Build a new Xelement with the original root and orderded "employee" elements.
var result = new XElement(xml.Root.Name,
from employee in orderedEmployees
select new XElement(employee)
);
又快又脏,只是为了给你一个想法:
var sorted = new XDocument(
new XElement(
"employees",
ORIGINAL_XDOC.Descendants("employee")
.OrderBy(e => e.Descendants("lastName")
.Single()
.Value)
.ThenBy(e => e.Descendants("firstName")
.Single()
.Value)));