2

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.