Search code examples
xmlxml-parsingxml-namespacesjdomjdom-2

Can we change the XML namespace variable name in JDOM?


I've an XML:

<OTC_RM xmlns="OTC_RM_11-0" xmlns:ns2="http://www.fpml.org/2010/FpML-4-9">

I wish to change the namespace variable name from ns2 to something else say fp using JDOM. And the change should reflect all across the XML document.

Is it possible?


Solution

  • Changing the name is easy enough, (delete, and replace the namespace). Unfortunately, you will not likely be able to do it for actual elements that use that namespace.

    The simple solution is (assuming you have an Element instance otcrm:

    Namespace fp = Namespace.getNamespace("fp", "http://www.fpml.org/2010/FpML-4-9");
    Namespace ns2 = Namespace.getNamespace("ns2", "http://www.fpml.org/2010/FpML-4-9");
    
    otcrm.addNamespaceDeclaration(fp);
    otcrm.removeNamespaceDeclaration(ns2);
    

    That will remove the ns2 declaration, and add the fp declaration. This is just for the specified Element, though. Any child Elements that use(d) the ns2 namespace prefix will simply "re-declare" it, and continue with that prefix.

    The real trick is to iterate all child elements, and change any instances where it is used.

    for (Element e : otcrm.getDescendants(Filters.element())) {
        if (e.getNamespace() == ns2) {
            e.setNamespace(fp);
        }
    }
    

    That will change all element prefixes to the new one.