0

When I add xmls attribute to my root element this code through a exception at third line " Object reference not set to an instance of an object" but after removing xmls attribute from root element it it works fine.

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("file.xml");    
MessageBox.Show(xmlDoc.SelectSingleNode("person/name").InnerText);

here is my xmlfile

<?xml version="1.0" encoding="utf-8"?>
<person xmlns="namespace path">
<name>myname</name>
</person>

I want to know why it does not works after adding xmlns attribute to my root element. Do I have to use another method for parsing ?.

3 Answers 3

1

You need to add namespace messenger to resolve namespaces to your xml file.

Consider this example

XML File

<?xml version="1.0" encoding="utf-8"?>
  <person xmlns="http://www.findpersonName.com"> // Could be any namespace
      <name>myname</name>
  </person>

and in your code

         XmlDocument doc = new XmlDocument();
        doc.Load("file.xml");

        //Create an XmlNamespaceManager for resolving namespaces.
        XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
        nsmgr.AddNamespace("ab", "http://www.findpersonName.com");
        MessageBox.Show(doc.SelectSingleNode("//ab:name", nsmgr).InnerText);
Sign up to request clarification or add additional context in comments.

1 Comment

i did not created this xml file and i did not know about namespace so is it necessary that the namespace should be in my system.
1

Note

If the XPath expression does not include a prefix, it is assumed that the namespace URI is the empty namespace. If your XML includes a default namespace, you must still add a prefix and namespace URI to the XmlNamespaceManager; otherwise, you will not get a node selected. For more information, see Select Nodes Using XPath Navigation.

XmlNamespaceManager ns = new XmlNamespaceManager(xmldoc.NameTable);
ns.AddNamespace("something", "http://or.other.com/init");
XmlNode node = xmldoc.SelectSingleNode("something:person/name", ns);

1 Comment

Almost, treemonkey: XmlNode node = xmldoc.SelectSingleNode("something:person/name", ns);
0

You may want to consider using XDocument and Linq to process your XML document.

The following example provides a rough example:

XDocument xDoc = XDocument.Load("file.xml"); 
var personNames = (from x in xDoc.Descendants("person").Descendants("name") select x).FirstOrDefault();  

How to Get XML Node from XDocument

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.