views:

310

answers:

2

Hello!

I have something like that as input:

<root xmlns="urn:my:main" 
    xmlns:a="urn:my:a" xmlns:b="urn:my:b">

    ...
</root>

And want to have something like that as output:

<MY_main:root xmlns:MY_main="urn:my:main" 
    xmlns:MY_a="urn:my:a" xmlns:MY_b="urn:my:b">

    ...
</MY_main:root>

... or the other way round.

How do I achieve this using DOM in an elegant way?
That is, without searching for attribute names starting with "xmlns".

+1  A: 

You will not find the xmlns attributes in your DOM, they are not part of the DOM.

You may have some success if you find the nodes you want (getElementsByTagNameNS) and set their qualifiedName (qname) to a new value containing the prefix you like. Then re-generate the XML document.

By the way, the namespace prefix (which is what you are trying to change) is largely irrelevant when using any sane XML parser. The namespace URI is what counts. Why would you want to set the prefix to a specific value?

Gerco Dries
Because I need user-readable XML (normally an oxymoron) in some special case. Thank you for the answer!
ivan_ivanovich_ivanoff
A: 

I have used the following jdom stub to remove all the namespace references:

Element rootElement = new SAXBuilder().build(contents).getRootElement();

for (Iterator i = rootElement.getDescendants(new ElementFilter()); i.hasNext();) {
    Element el = (Element) i.next();
    if (el.getNamespace() != null) el.setNamespace(null);
}

return rootElement;

Reading and writing the xml is done as normal. If you are just after human readable output that should do the job. If however you need to convert back you may have a problem.

The following may work to replace the namespaces with a more friendly version based on your example (untested):

rootElement.setNamespace(Namespace.getNamespace("MY_Main", "urn:my:main"));
rootElement.addNamespaceDeclaration(Namespace.getNamespace("MY_a", "urn:my:a"))
rootElement.addNamespaceDeclaration(Namespace.getNamespace("MY_b", "urn:my:b"))
Michael Rutherfurd