Selecting nodes with no namespace using XPath in C#

When nodes in an XML document has no prefix at all you would think that they are associated with the default namespace, but apparently this is not the case.

Those nodes are considered not associated with any namespace at all. So to select them using XPath, in the NamespaceManager first add the default namespace with any arbitrary prefix of your choosing but not string.Empty, for example:

namespaceManager.AddNameSpace(“x”, “http://…”);

Here x is just a randomly chosen prefix

Then, you can use XPath to select nodes using the prefix you just added

doc.SelectNodes(“//x:NodeName”, namespaceManager);

I spent 2 hours to figure this out, talk about wasting time.

Leave a Reply

Your email address will not be published. Required fields are marked *