user2960190 user2960190 - 1 year ago 88
Java Question

Remove Namespace from tag

I searched in SO but I did not found nothing that solves my problem. I hope some one can help me.

I am building a XML file and I need to remove the Namespace


That is my code

Document xmlDocument = new Document();
Namespace ns1 = Namespace.getNamespace("urn:iso:std:iso:20022:tech:xsd:pain.001.001.03");
Namespace ns2 = Namespace.getNamespace("xsi", "");
Element root = new Element("Document", ns1);
Element CstmrCdtTrfInitn = new Element("CstmrCdtTrfInitn");

PrintDocumentHandler pdh = new PrintDocumentHandler();
request.getSession(false).setAttribute("pdh", pdh);

ByteArrayOutputStream sos = new ByteArrayOutputStream();
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
Format format = outputter.getFormat();
outputter.output(root, sos);
return sos;

And this is the created XML-File

<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns:xsi="" xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
<CstmrCdtTrfInitn xmlns=""/>

I have to remove the namespace
from the tag

Many thanks in advance.

Answer Source

Namespace declaration without prefix (xmlns="...") is known as default namespace. Notice that, unlike prefixed namespace, descendant elements without prefix inherit ancestor's default namespace implicitly. So in the XML below, <CstmrCdtTrfInitn> is considered in the namespace urn:iso:std:iso:20022:tech:xsd:pain.001.001.03 :

<Document xmlns:xsi="" xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">

If this is the wanted result, instead of trying to remove xmlns="" later, you should try to create CstmrCdtTrfInitn using the same namespace as Document in the first place :

Element CstmrCdtTrfInitn = new Element("CstmrCdtTrfInitn", ns1);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download