views:

719

answers:

1

Problem description: Read an xml file, traverse to a particular node (element), if it does not have a particular namespace declaration, add the required namespace declaration, and write out the file.

I need to do this in C++ using Microsoft's MSXML DOM APIs. The namespaceURI property on IXMLDOMNode COM object is read-only according to this msdn reference. Appreciate any workarounds.

Edit: I spent quite some time on a workaround: Create a new sibling node in the same document with the namespace I need, then move all the child elements of the original node to this new node, then delete the original node. Well, this does not work, because the child nodes are going to keep whatever default namespace they had before.

And then this simple idea hit me and it works but I am not sure if it will bite me in the future: just create an "xmlns" attribute on the element, giving it the desired namespace value! Any comments?

+1  A: 

Guessing that you mean to add a default namespace to an element its first important to understand that this is not strictly possible. The namespace that an element's name belongs to forms it fully qualified name hence "adding" a default namespace is tantamount to renaming the element. There is no mechanism built into the DOM to rename elements.

The strictest approach would be to process the XML as an input to a transform (either in code or via XSLT) that generates the corrected XML output.

However a pragmatic solution would be to use some string processing like RegEx to find the element and inject the xmlns attribute. Personally I prefer the former.

AnthonyWJones