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

Kjartan
  • 18,591
  • 15
  • 71
  • 96
Raj
  • 33
  • 1
  • 1
  • 8

3 Answers3

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);
Community
  • 1
  • 1
Treemonkey
  • 2,133
  • 11
  • 24
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);
Rohit
  • 10,056
  • 7
  • 50
  • 82
  • 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. – Raj Mar 31 '15 at 12:42
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

Community
  • 1
  • 1
Seymour
  • 7,043
  • 12
  • 44
  • 51