0

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

5
  • Why -1 is there anything wrong ?? Commented Apr 6, 2015 at 9:49
  • catch this link stackoverflow.com/questions/18250671/… Commented Apr 6, 2015 at 9:52
  • someone answer this question previously Commented Apr 6, 2015 at 9:54
  • 1
    That link doesn't actually answer the question although it is the same problem. It isn't to do with schemas, it's to do with changing the default namespace. Commented Apr 6, 2015 at 10:06
  • That link does not answer the probelm Commented Apr 6, 2015 at 10:16

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.