Search code examples
c#xpathnullselectsinglenode

XPath Query always returns NULL only on some queries in SingleNodeSelect


<?xml version="1.0" encoding="utf-16"?>
<users>
  <user number="0772247157">
    <step stepnumber="1">complete</step>
    <step stepnumber="2">complete</step>
    <step stepnumber="3">complete</step>
  </user>
  <user number="0772247158">
    <step stepnumber="1">complete</step>
    <step stepnumber="2">complete</step>
  </user>
  <user number="0772247159">
    <step stepnumber="1">complete</step>
  </user> 
</users>

Queries such as

//user[@number='0772243950'] and //user[@number=0772243950]/step[last()] works without any trouble which uses SelectSingleNode method.

However the following function ALWAYS returns null. It works perfectly with XPath Visualizer and i double checked with an online XPath evaluator.

public bool checkStepExists(string Number, string StepNumber)
{
    string XPathQuery = "//user[@number=" + Number + "]/step[@stepnumber=" + StepNumber + "]";

    XmlNode Search = SettingsFile.SelectSingleNode(XPathQuery);      

    if (Search == null)
       return false;
    else
       return true;            
}

I searched on SO before asking this question and all points to namespace problems. But what I can't understand is that this is a local XML file which does not have a namespace. OR, should I ALWAYS have a namespace and a prefix and use it?


Solution

  • Within your string XPathQuery I think you need to quote the numbers. Like this:

    string XPathQuery = "//user[@number=\"" + Number + "\"]/step[@stepnumber=\"" + StepNumber + "\"]";