我将以下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>
然后<firstname>
使用Linq to XML对所有节点进行排序。因此,在应用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>
答案 0 :(得分:1)
快速又脏,只是为了给你一个想法:
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)));
答案 1 :(得分:1)
// 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)
);