XPathExpression AddSort

时间:2011-10-18 10:14:59

标签: c# xml xpath

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

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

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>

1 个答案:

答案 0 :(得分:3)

看起来像是一个重复的问题 - 请参阅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);