是否可以使用XPathExpression.AddSort对元素进行排序,而不仅对节点进行排序?

如果我稍稍更改了MSDN文档上的示例代码XPathExpression.AddSort,所以我请求一个元素而不是整个节点,则排序顺序不起作用。

var doc = new XPathDocument("contosoBooks.xml");
var nav = doc.CreateNavigator();

var expr = nav.Compile("/bookstore/book/title");

expr.AddSort("title", XmlSortOrder.Descending,
               XmlCaseOrder.None, "", XmlDataType.Number);

var iterator = nav.Select(expr);
while (iterator.MoveNext())
{
    Console.WriteLine(iterator.Current);
}


我期望这个输出:

The Gorgias
The Confidence Man
The Autobiography of Benjamin Franklin


但是输出是这样的:

The Autobiography of Benjamin Franklin
The Confidence Man
The Gorgias


这是xml文件供您参考

<?xml version="1.0" encoding="utf-8" ?>
<bookstore>
  <book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0">
    <title>The Autobiography of Benjamin Franklin</title>
    <author>
      <first-name>Benjamin</first-name>
      <last-name>Franklin</last-name>
    </author>
    <price>8.99</price>
  </book>
  <book genre="novel" publicationdate="1967-11-17" ISBN="0-201-63361-2">
    <title>The Confidence Man</title>
    <author>
      <first-name>Herman</first-name>
      <last-name>Melville</last-name>
    </author>
    <price>11.99</price>
  </book>
  <book genre="philosophy" publicationdate="1991-02-15" ISBN="1-861001-57-6">
    <title>The Gorgias</title>
    <author>
      <name>Plato</name>
    </author>
    <price>9.99</price>
  </book>
</bookstore>

最佳答案

看起来像是重复的问题-请参见XPathExpression AddSort fails

因此,在您的情况下,代码必须类似于:

var expr = nav.Compile("/bookstore/book");

expr.AddSort("title", XmlSortOrder.Descending,
           XmlCaseOrder.None, "", XmlDataType.Number);


要么

var expr = nav.Compile("/bookstore/book/title");

expr.AddSort(".", XmlSortOrder.Descending,
           XmlCaseOrder.None, "", XmlDataType.Number);

09-28 06:54