I have this XML document:
<?xml version="1.0" encoding="utf-8"?>
<document xmlns="file:///someurl/goes.here">
<levelone>
<leveltwo>
<title>Test Title</title>
<item>Item 1</item>
<item>Item 2</item>
<item>Item 3</item>
</leveltwo>
</levelone>
</document>
And this code:
static void Main(string[] args)
{
XmlDocument fileIn = new XmlDocument();
fileIn.Load("XMLFile1.xml");
XmlNamespaceManager nsm = new XmlNamespaceManager(fileIn.NameTable);
nsm.AddNamespace(String.Empty, "file:///someurl/goes.here");
XmlNode docElem = fileIn.DocumentElement;
string title = docElem.SelectSingleNode("levelone/leveltwo/title", nsm).InnerText;
Console.WriteLine("Title: " + title);
Console.WriteLine("Items: " + docElem.SelectNodes("//item", nsm).Count);
Environment.Exit(0);
}
If I run this, I get a NullReferenceException
when I attempt to get the InnerText
of the node I'm attempting to select for title
. However, if I change my AddNamespace
call to nsm.AddNamespace("a", "file:///someurl/goes.here")
and update all of my XPaths to use that a
namespace, then it works fine.
My understanding is that elements without the prefixes in an XPath refer to the empty namespace. String.Empty
is said to be for the empty namespace in MSDN's docs, and I'm giving the NamespaceManager
the correct namespace URI for the empty namespace. Yet it doesn't seem to be working and I find myself having to make a dummy namespace in the manager to get it to work right, which is really annoying. Why do I have to use this, or any workaround?
I am not looking for a way to get my code to run, I know of a couple ways and detailed one widely-accepted method above. I want to know why my understanding of the documentation is resulting in broken code - e.g. is this an issue on Microsoft's end or am I just misunderstanding something?