views:

101

answers:

1

In .Net I do this:

XmlNamespaceManager nsMan = new XmlNamespaceManager(xmlDoc.NameTable);
XmlNodeList nlImages = xmlDoc.SelectNodes("//v:imagedata", nsMan);

And I get this exception:

Namespace prefix 'v' is not defined.

But if I break the process and write this statement:

xmlDoc.NameTable.Get("v")

I get "v" out, so the namespace is defined ...right?

Anyway, in order to get this to work I have to add this:

nsMan.AddNamespace("v", "urn:schemas-microsoft-com:vml");

To get that XPath query to work (I checked and the v namespace is defined in the source xml document), so why doesn't this work as it seems it should?

Thanks for the helps,

-nomad311

+1  A: 

This is a quirk of how the XmlNode object works, and accesses Namespaces within an XML document.

Unfortunately, you must use an XmlNamespaceManager (as you're doing in your code posted in your question) in order to use namespaces within the XML document that you're processing.

From the MSDN documentation for the .SelectNodes method of the XmlNode object:

XPath expressions can include namespaces. Namespace resolution is supported using the XmlNamespaceManager. If the XPath expression includes a prefix, the prefix and namespace URI pair must be added to the XmlNamespaceManager.

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 any nodes selected. For more information, see Select Nodes Using XPath Navigation.

For what it's worth, manipulating XML documents/nodes using LINQ-To-XML is much easier, and more "fluent".

CraigTP