使用xpathnavigator通过连接常量选择xpathexpression响应

时间:2013-04-23 12:40:03

标签: c# xpath xpathnavigator

我有一个库函数,如下所示

private static string Parse(XPathNavigator xNav, XPathExpression xPathExpression)
    {
        string result = string.Empty;
        XPathNodeIterator xpathIterator = xNav.Select(xPathExpression.Clone());

        while (xpathIterator.MoveNext())
        {
            result = result + xpathIterator.Current.TypedValue + "#";
        }

        return result;
    }

还有一个XML文件,如下所示

<Account account_no ="100">
<Name>Hello</Name>
</Account> 

现在我需要写一个xpath,它会返回account_no连接一些常量

我写了类似下面的代码

        XPathDocument doc = new XPathDocument(@"..\..\test.xml", XmlSpace.Default);
        XPathNavigator xNav = doc.CreateNavigator();
        string xpath = "concat('Account No', /Account/@account_no)";
        XPathExpression xPathExpression = XPathExpression.Compile(xpath);
        string result = Parse(xNav, xPathExpression);

我期待的结果是account_no为它添加了一些文本常量。所以我把xpath写成了concat('Account No',/ Account / @ account_no)。但这没有用,在xNav.Select()失败了。请帮助我如何编写适当的xpath来获得所需的结果。我没有自由改变解析函数,无论我能做什么,我都应该只使用xpath字符串。

谢谢。

1 个答案:

答案 0 :(得分:0)

如果您将Parse()方法修改为这样,那么它应该有效:

private static string Parse(XPathNavigator xNav, XPathExpression xPathExpression)
{
    string result = string.Empty;
    object selected = xNav.Evaluate(xPathExpression.Clone());

    XPathNodeIterator iterator = selected as XPathNodeIterator;
    if (iterator != null)
    {
        result = string.Concat(iterator.OfType<XPathNavigator>()
                                       .Select(n => n.TypedValue + "#"));
    }
    else
    {
        result = selected.ToString();
    }

    return result;
}