How do I resolve the error “Expression must evaluate to a node-set” when checking for the existence of a node?

后端 未结 3 663
盖世英雄少女心
盖世英雄少女心 2021-01-17 10:28

I\'m attempting to check for the existence of a node using the following .NET code:

xmlDocument.SelectSingleNode(
        String.Format(\"//ErrorTable/Projec         


        
相关标签:
3条回答
  • 2021-01-17 10:49

    The expression given evaluates to a boolean, not a node-set. I assume you want to check whether the ProjectName equals the parametrized text. In this case you need to write

    //ErrorTable/ProjectName[text()='{0}']
    

    This gives you a list of all nodes (a nodeset) matching the given condition. This list may be empty, in which case the C#-Expression in your sample will return null.

    As an afterthought: You can use the original xpath expression, but not with SelectSingleNode, but with Evaluate, like this:

    (bool)xmlDocument.CreateNavigator().Evaluate(String.Format("//ErrorTable/ProjectName/text()='{0}'", projectName));
    
    0 讨论(0)
  • 2021-01-17 10:51

    Try:

    Node node = xmlDocument.SelectSingleNode(String.Format("//ErrorTable/ProjectName = '{0}'", projectName));
    
    if (node != null) {
        // and so on
    }
    

    Edit: silly error

    0 讨论(0)
  • 2021-01-17 11:11

    The XPath expression contained a subtle error. It should have been:

    xmlDocument.SelectSingleNode(String.Format("//ErrorTable/ProjectName[text()='{0}']", projectName));
    

    The previous expression was evaluating to a boolean, which explains the exception error. Thanks for the help!

    0 讨论(0)
提交回复
热议问题