我收到一個異常:System.Xml.XPath.XPathException:表達式必須求值爲節點集。xpath表達式count()失敗,出現異常,Expression必須求值爲節點集
當我運行這個代碼,我期待計算節點的數量,我做錯了什麼?
var doc = new XPathDocument("contosoBooks.xml");
var nav = doc.CreateNavigator();
var expr = nav.Compile("count(//bookstore/book)");
var iterator = nav.Select(expr);
while (iterator.MoveNext())
{
if (iterator.Current != null && !iterator.Current.HasChildren) continue;
if (iterator.Current != null)
{
var childIter = iterator.Current.SelectChildren(XPathNodeType.Element);
while (childIter.MoveNext())
{
if (childIter.Current != null) Console.WriteLine(childIter.Current.Value);
}
}
}
我的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>
注:謝謝你的effords來幫助我。我想出了這個解決方案:
var doc = new XPathDocument("contosoBooks.xml");
var nav = doc.CreateNavigator();
const string query = "count(//bookstore/book)";
var expr = nav.Compile(query);
switch (expr.ReturnType)
{
case XPathResultType.Number:
Console.WriteLine(nav.Evaluate(query));
break;
case XPathResultType.String:
// case XPathResultType.Navigator:
Console.WriteLine(nav.Evaluate(query));
break;
case XPathResultType.Boolean:
Console.WriteLine(nav.Evaluate(query));
break;
case XPathResultType.NodeSet:
var nodes = nav.Select(expr);
while (nodes.MoveNext())
{
if (nodes.Current != null && !nodes.Current.HasChildren) continue;
if (nodes.Current == null) continue;
var childIter = nodes.Current.SelectChildren(XPathNodeType.Element);
while (childIter.MoveNext())
{
if (childIter.Current != null) Console.WriteLine(childIter.Current.Value);
}
}
break;
case XPathResultType.Any:
Console.WriteLine(nav.Evaluate(query));
break;
default:
Console.WriteLine(nav.Evaluate(query));
break;
}
+1對於有趣的細節,它返回一個雙 - 有點意外。 –