I am tryng to sort a result from an xpath query but it fails.
Ooutput:
ABC
DEF
But I am expecting:
DEF
ABC
The source code looks like this, it uses an XML expression and sorts the result:
var doc = new XPathDocument("testmsg2.xml");
var nav = doc.CreateNavigator();
const string query = "//Z/X/Code";
var expr = nav.Compile(query);
expr.AddSort("Code",
XmlSortOrder.Descending,
XmlCaseOrder.None,
"",
XmlDataType.Text);
switch (expr.ReturnType)
{
case XPathResultType.NodeSet:
var nodes = (XPathNodeIterator)nav.Evaluate(expr);
while (nodes != null && nodes.MoveNext())
{
if (nodes.Current == null)
continue;
if (nodes.Current.HasChildren)
{
var childIter = nodes.Current.SelectChildren(XPathNodeType.All);
while (childIter.MoveNext())
{
if (childIter.Current != null)
Console.WriteLine(childIter.Current.Value);
}
}
else
{
Console.WriteLine(nodes.Current.Value);
}
}
break;
}
The XML file is simplified for this example:
<?xml version="1.0" encoding="utf-8"?>
<Z>
<X>
<Code>ABC</Code>
</X>
<X>
<Code>DEF</Code>
</X>
</Z>
The
AddSortmethod takes an XPath expression that is contextually bound to theXPathExpressionyou’ve compiled. In your case, theXPathExpressionis compiled against the<Code>element. DoingAddSort("Code")implies that you have the following XML:Instead, you can either compile your expression to
X:Or you can sort on the current node (being
Code),.: