Reputation: 46
XML is small and looks like below
<?xml version="1.0" encoding="UTF-8"?><userdetails xsi:schemaLocation="urn:MyNamespace loginasp.xsd" xmlns="urn:MyNamespace" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><username>909</username><password>madhuri1</password></userdetails>
For parsing this XML i have written the below code.
XmlDocument doc = new XmlDocument();
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(s);//S contains above XML
XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());
nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
string emp_id = xDoc.SelectSingleNode("/userdetails/username", nsmgr).InnerText;
I am not able to select the single NODExDoc.SelectSingleNode("/userdetails/username", nsmgr)
is null
Is there any else i need to do to parse XML or My XML is wrong.Without namespace it works fine
Upvotes: 0
Views: 75
Reputation: 2345
You need to add your default namespace into the XmlNamespaceManager.
nsmgr.AddNamespace("t", "urn:MyNamespace");
And then use this namespace in your XPath Query
string emp_id = xDoc.SelectSingleNode("/t:userdetails/t:username", nsmgr).InnerText;
Upvotes: 1