views:

60

answers:

2

I have a "plain" XmlDocument loaded like so:

<root>
    <element1 />
    <element2></element2>
</root>

and want to qualify the elements with namespaces like so while the object model is loaded

<abc:root xmlns:abc="urn:something">
    <abc:element1 />
    <abc:element2></abc:element2>
</abc:root>

before writing it out.

A: 

Unfortunately, you can't just change the namespace for a node. Those properties are read-only.

You're going to be stuck creating a new document either by recursion or by using an XSLT.

John Saunders
A: 

One dirty trick is if you are reading the XML from a store/string then you can extend XmlTextReader to change the loaded document's namespace (although I do not know if is going to be helpful as you seem to imply you already have a loaded document, which admittedly must have come from somewhere).

So for example:

class MyXmlReader : XmlTextReader
{
    public MyXmlReader(TextReader r) : base(r)
    {
    }

    public override string Prefix
    {
        get
        {
            return "abc";
        }
    }

    public override string NamespaceURI
    {
        get
        {
            return "urn:something";
        }
    }
}

Then you can use it like XmlReader r = new MyXmlReader(new StringReader("<root/>")); or similar.

-= EDIT =-

Now I think about it there is a far more obvious way, override the XmlWriter instead :)

e.g.

class MyXmlWriter : XmlTextWriter
{
    public MyXmlWriter(TextWriter w)
        : base(w)
    {
    }

    public override void WriteStartElement(string prefix, string localName, string ns)
    {
        base.WriteStartElement("abc", localName, "urn-something");
    }
}

Job done.

tyranid