0

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

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 字符串。

谢谢你。

4

1 回答 1

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;
}
于 2013-04-23T12:49:17.493 回答