views:

25

answers:

2
<?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?

+2  A: 

Perhaps try it with the extra quotes?

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

I would also be interested in checking if there is any whitespace adding around Number or StepNumber. Basically: what is the actual string query you pass in? (after concatenation etc).

Marc Gravell
@Marc: Actually XPath seems to be forgiving whether the ' ' were included or not. Talk about SQL :P
Ranhiru Cooray
+2  A: 

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

string XPathQuery = "//user[@number=\"" + Number + "\"]/step[@stepnumber=\"" + StepNumber + "\"]";
stupid-phil
Marking phil's answer as it actually helped me to find the error :)
Ranhiru Cooray
@Ranhiru - many thanks
stupid-phil