blogs.conchango.com

welcome to the conchango blogging site
Welcome to blogs.conchango.com Sign in | Join | Help
in Search

Merrick Chaffer's Blog

XPath and Namespaces (and msbuild sdc xml.modifyfile task)

xmlDocument.SelectNodes with xmlns="..."

Spent most of today wondering why I couldn't update a connection string in a web.config file using xpath which had the default namespace for xmlns  defined at the root of the config file. e.g. <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">

Turns out that you have to add a XmlNamespaceManager to your document.SelectNodes xpath query, which has had a prefix added to it first, and alter your xpath to include these prefix.

E.g.

xmlNamespaceManager.AddNamespace("ns", xmlDocument.DocumentElement.NamespaceURI)

then

doc.SelectNodes("/ns:configuration/ns:connectionStrings") - will actually work.

The funny thing is after figuring all this out for myself, a colleague suggested that we simply use the Xml.ModifyFile task in the Microsoft SDC tasks, which happens to cope for this sort of thing within the file. It also appears as if someone has come across this problem before as well...

http://www.codeplex.com/sdctasks/Thread/View.aspx?ThreadId=13167

another very concise reference if you're using .net directly to update documents using xpath queries is below...

http://msdn2.microsoft.com/en-us/library/ms950779.aspx (checkout the examples towards the middle of this page that show that you should expect NO RESULTS if you do not prefix your xpath).

SAVING without xmlns="" appearing on your element node

To get a document element created without the extra xmlns="" appearing as an attribute in your newly created element, you must use the 3rd overload as follows ..

xmlDocument.CreateElement("", "myNodeName", xmlDocument.DocumentElement.NamespaceURI)

Published 29 November 2007 15:00 by merrick.chaffer

Comments

No Comments
Anonymous comments are disabled
Powered by Community Server (Personal Edition), by Telligent Systems