Xml/Xslt - Need help in reading the xmlattribute based on certion condition using XPathNavigator

Asked By Rahul Khanna on 23-May-13 12:05 PM
Hi all,

Need help in reading the xmlattribute value based on certion condition using XPathNavigator.
here is my sample.xml file:
<?xml version="1.0" encoding="utf-8"?>
<WorldCountry> 
   <Country>
     <Name>India</Name>      
      <states>
<states name ="Hariyana" code="HA"/>
    <states name ="Punjab" code="PU"/>
<states name ="Gujrat" code="GU"/>
<states name ="Rajsthan" code="RA"/>
<states name ="Karnataka" code="KA"/>
<states name ="Kerala" code="KR"/>
        <states name ="Maharastra" code="MA"/>      
      </states>
     </Country>
   </WorldCountry>
  
   
based on states name states code should return if we give states name as Maharastra then state code should return as MA not other.Some thing like below code but its not working...


            XPathDocument document = new XPathDocument("D:/Sample.xml");
            XPathNavigator navigator = document.CreateNavigator();
            XPathNavigator node = navigator.SelectSingleNode("WorldCountry/Country/states[@name='Maharastra']");
            return states code of Maharastra.
Robbe Morris replied to Rahul Khanna on 23-May-13 12:11 PM
What is in the "node" variable?  Your syntax is correct.

http://www.nullskull.com/a/1625/xml--xpath-query-examples.aspx

If "node" is null, you may want to try a route path on your query.

//WorldCountry

instead of

WorldCountry
Rahul Khanna replied to Robbe Morris on 23-May-13 12:42 PM
thanks for your reply...node variable always returning null after changing like below also:
//WorldCountry/Country/states[@name='Maharastra']
Robbe Morris replied to Rahul Khanna on 23-May-13 12:47 PM
I think you want the list of states to have a node name of "state" not states.  Assuming you can't change that, then I think your query needs to be:

//WorldCountry/Country/states/states[@name='Maharastra']
Rahul Khanna replied to Robbe Morris on 23-May-13 01:16 PM
yes you are absolutely right.But when I am trying to  return the states code by below code...I am getting the exception object reference not set to instance object.

XPathNavigator node = navigator.SelectSingleNode("//WorldCountry/Country/states/states[@name='Maharastra']");
string statescode = node.SelectSingleNode("code").Value.ToString();
Robbe Morris replied to Rahul Khanna on 23-May-13 01:22 PM
"code" is not a node.  It is an attribute value.
 

node.Attributes.GetNamedItem("code").Value