You need a transformer. Check below the modified method :

public static String removeNameSpace(String xml) {


        try {
             TransformerFactory tf = TransformerFactory.newInstance();
             Transformer transformer = tf.newTransformer();
             transformer.setOutputProperty( OutputKeys.METHOD, "xml" );
             transformer.setOutputProperty( OutputKeys.INDENT, "false" );
            System.out.println("before xml = " + xml);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            InputSource inputSource = new InputSource(new StringReader(xml));
            Document xmlDoc = builder.parse(inputSource);
            Node root = xmlDoc.getDocumentElement();
            NodeList rootchildren = root.getChildNodes();
            Element newroot = xmlDoc.createElement(root.getNodeName());
            for (int i = 0; i < rootchildren.getLength(); i++) {
                newroot.appendChild(rootchildren.item(i).cloneNode(true));
            }
            xmlDoc.replaceChild(newroot, root);
            DOMSource requestXMLSource = new DOMSource( xmlDoc.getDocumentElement() );
            StringWriter requestXMLStringWriter = new StringWriter();
            StreamResult requestXMLStreamResult = new StreamResult( requestXMLStringWriter );            
            transformer.transform( requestXMLSource, requestXMLStreamResult );
            String modifiedRequestXML = requestXMLStringWriter.toString();

            return modifiedRequestXML;
        } catch (Exception e) {
            System.out.println("Could not parse message as xml: " + e.getMessage());
        }
        return "";
    }

Output :

before xml = <?xml version="1.0" encoding="UTF-8"?><Payment xmlns="http://api.com/schema/store/1.0"><Store>abc</Store></Payment>
afterNsRemoval = <?xml version="1.0" encoding="UTF-8"?><Payment><Store>abc</Store></Payment>
Answer from SomeDude on Stack Overflow
Top answer
1 of 5
3

You need a transformer. Check below the modified method :

public static String removeNameSpace(String xml) {


        try {
             TransformerFactory tf = TransformerFactory.newInstance();
             Transformer transformer = tf.newTransformer();
             transformer.setOutputProperty( OutputKeys.METHOD, "xml" );
             transformer.setOutputProperty( OutputKeys.INDENT, "false" );
            System.out.println("before xml = " + xml);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            InputSource inputSource = new InputSource(new StringReader(xml));
            Document xmlDoc = builder.parse(inputSource);
            Node root = xmlDoc.getDocumentElement();
            NodeList rootchildren = root.getChildNodes();
            Element newroot = xmlDoc.createElement(root.getNodeName());
            for (int i = 0; i < rootchildren.getLength(); i++) {
                newroot.appendChild(rootchildren.item(i).cloneNode(true));
            }
            xmlDoc.replaceChild(newroot, root);
            DOMSource requestXMLSource = new DOMSource( xmlDoc.getDocumentElement() );
            StringWriter requestXMLStringWriter = new StringWriter();
            StreamResult requestXMLStreamResult = new StreamResult( requestXMLStringWriter );            
            transformer.transform( requestXMLSource, requestXMLStreamResult );
            String modifiedRequestXML = requestXMLStringWriter.toString();

            return modifiedRequestXML;
        } catch (Exception e) {
            System.out.println("Could not parse message as xml: " + e.getMessage());
        }
        return "";
    }

Output :

before xml = <?xml version="1.0" encoding="UTF-8"?><Payment xmlns="http://api.com/schema/store/1.0"><Store>abc</Store></Payment>
afterNsRemoval = <?xml version="1.0" encoding="UTF-8"?><Payment><Store>abc</Store></Payment>
2 of 5
2

Consider XSLT as removing declared/undeclared namespace is a regular task. Here, no third-party modules are needed as base Java is equipped with an XSLT 1.0 processor. Additionally, no loops or XML tags/attribs re-creation is handled as XSLT takes care of the transformation.

import java.io.*;

import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class XPathUtils {
    public static void main(String[] args) {

        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Payment xmlns=\"http://api.com/schema/store/1.0\"><Store>abc</Store></Payment>";
        String afterNsRemoval = removeNameSpace(xml);
        System.out.println("afterNsRemoval = " + afterNsRemoval);
    }

    public static String removeNameSpace(String xml) {
        try{
            String xslStr = String.join("\n",
                "<xsl:transform xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">",
                "<xsl:output version=\"1.0\" encoding=\"UTF-8\" indent=\"no\"/>",
                "<xsl:strip-space elements=\"*\"/>",                          
                "  <xsl:template match=\"@*|node()\">",
                "   <xsl:element name=\"{local-name()}\">",
                "     <xsl:apply-templates select=\"@*|node()\"/>",
                "  </xsl:element>",
                "  </xsl:template>",  
                "  <xsl:template match=\"text()\">",
                "    <xsl:copy/>",
                "  </xsl:template>",                                  
                "</xsl:transform>");

            // Parse XML and Build Document
            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            Document doc = db.parse (is);                      

            // Parse XSLT and Configure Transformer
            Source xslt = new StreamSource(new StringReader(xslStr));
            Transformer tf = TransformerFactory.newInstance().newTransformer(xslt);

            // Output Result to String
            DOMSource source = new DOMSource(doc);
            StringWriter outWriter = new StringWriter();
            StreamResult strresult = new StreamResult( outWriter );        
            tf.transform(source, strresult);
            StringBuffer sb = outWriter.getBuffer(); 
            String finalstring = sb.toString();

            return(finalstring);

        } catch (Exception e) {
            System.out.println("Could not parse message as xml: " + e.getMessage());
        }
            return "";    
    }
}
🌐
Experts Exchange
experts-exchange.com › questions › 28583763 › Remove-attribute-form-XML-in-java.html
Solved: Remove attribute form XML in java | Experts Exchange
December 18, 2014 - How can I remove an attribute from XML? Below code is not working. private static Document removeXMLNSAttribute(Document doc) throws ParserConfigurationException, SAXException, IOException { NodeList nodeList = doc.getElementsByTagName("*"); for ( int i = 0; i < nodeList.getLength(); i++ ) { Element ele = (Element) nodeList.item(i); if (ele.hasAttribute("xmlns")) { ele.removeAttribute("xmlns"); } } return doc; }
🌐
Coderanch
coderanch.com › t › 633633 › languages › remove-namespace-attributes-XML-java
How to remove namespace/attributes in XML through java (XML forum at Coderanch)
If you hate that much that information ... of data binding. [1] Validation neutral/agnostic [1.1] Pass the output of marshalling immediately to an xslt to get rid of the xsi:nil attribute and xmlns:xsi decalration....
🌐
CodingTechRoom
codingtechroom.com › question › -remove-xmlns-attribute-root-xml-java
How to Remove the `xmlns` Attribute from the Root Element in XML Using Java - CodingTechRoom
Use the Document Object Model (DOM) to manipulate XML and remove the `xmlns` attribute. Ensure to have the necessary XML libraries included in your project. Example code demonstrates how to remove attributes using Java.
🌐
Oracle
download.oracle.com › javaee-archive › saaj.java.net › users › 2005 › 03 › 0021.html
Removing xmlns attribute
March 18, 2005 - Isn't enough that the xmlns- attribute is removed or do I have to do something else. I'm using folloing code to test my algorithm (JWSDP-1.5) /* * Created on 18.3.2005 */ package tests.com.wa.xmlda.webservice.jwsdp; import java.util.Iterator; import javax.xml.soap.MessageFactory; import ...
🌐
Tabnine
tabnine.com › home page › code › java › org.w3c.dom.element
org.w3c.dom.Element.removeAttributeNS java code examples | Tabnine
private static void removeXmlBase(Element e) { e.removeAttributeNS("http://www.w3.org/XML/1998/namespace", "base"); // NOI18N e.removeAttribute("xml:base"); // NOI18N } ... protected void namespace(Element element, String prefix, String uri) { String qname; if ("".equals(prefix) || prefix == null) { qname = "xmlns"; } else { qname = "xmlns:" + prefix; } // older version of Xerces (I confirmed that the bug is gone with Xerces 2.4.0) // have a problem of re-setting the same namespace attribute twice.
🌐
CodingTechRoom
codingtechroom.com › question › -remove-xmlns-xml-request
How to Remove xmlns="" from an XML Request - CodingTechRoom
If using Java, you can achieve ... Document doc = builder.parse(new InputSource(new StringReader(xmlString))); Element root = doc.getDocumentElement(); root.removeAttribute('xmlns'); // Removes the xmlns attribute....
🌐
HelpEzee
helpezee.wordpress.com › 2013 › 04 › 23 › remove-namespaces-from-xml-java
Remove namespaces from XML (Java) | HelpEzee
February 19, 2019 - Despite being not advisable to work without namespaces, here goes a couple of options to remove the namespaces from a xml instance: Using a Regex function in Java: public static String removeXmlStringNamespaceAndPreamble(String xmlString) { ...
Find elsewhere
Top answer
1 of 2
13

You can use xslt for that. Try

removeNs.xslt

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" />

    <xsl:template match="*">
        <xsl:element name="{local-name(.)}">
            <xsl:apply-templates select="@* | node()" />
        </xsl:element>
    </xsl:template>
    <xsl:template match="@*">
        <xsl:attribute name="{local-name(.)}">
      <xsl:value-of select="." />
    </xsl:attribute>
    </xsl:template>
</xsl:stylesheet>

Sample.java

import java.io.File;

import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class Sample {

    public static void main(String[] args) {
        try{
            TransformerFactory factory = TransformerFactory.newInstance();
        Source xslt = new StreamSource(new File("removeNs.xslt"));
        Transformer transformer = factory.newTransformer(xslt);

        Source text = new StreamSource(new File("data.xml"));
        transformer.transform(text, new StreamResult(new File("output.xml")));
        System.out.println("Done");
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }

}
2 of 2
1

Regex can be used for more information refer this

public static string RemoveAllXmlNamespace(string xmlData)
        {
            string xmlnsPattern = "\\s+xmlns\\s*(:\\w)?\\s*=\\s*\\\"(?<url>[^\\\"]*)\\\"";
            MatchCollection matchCol = Regex.Matches(xmlData, xmlnsPattern);

            foreach (Match m in matchCol)
            {
                xmlData = xmlData.Replace(m.ToString(), "");
            }
            return xmlData;
        }
   }

You can find a similar example here

Regex can be painful. you can also use this api (dom) to get rid of all namespaces.refer this

 import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;

    ...

    /**
     * Recursively renames the namespace of a node.
     * @param node the starting node.
     * @param namespace the new namespace. Supplying <tt>null</tt> removes the namespace.
     */
    public static void renameNamespaceRecursive(Node node, String namespace) {
        Document document = node.getOwnerDocument();
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            document.renameNode(node, namespace, node.getNodeName());
        }
        NodeList list = node.getChildNodes();
        for (int i = 0; i < list.getLength(); ++i) {
            renameNamespaceRecursive(list.item(i), namespace);
        }
    }
🌐
Stack Overflow
stackoverflow.com › questions › 67208667 › how-to-remove-an-attribute-from-xml-element
java - How to remove an attribute from xml element? - Stack Overflow
April 22, 2021 - ... That means you need to rename the elements (component, nonXMLBody, and text). Oh, too bad, elements cannot be renamed. Well then, you need to remove the elements and re-create them with the correct qualified names, while retaining all other ...
Top answer
1 of 9
15

Use the Regex function. This will solve this issue:

public static String removeXmlStringNamespaceAndPreamble(String xmlString) {
  return xmlString.replaceAll("(<\\?[^<]*\\?>)?", ""). /* remove preamble */
  replaceAll("xmlns.*?(\"|\').*?(\"|\')", "") /* remove xmlns declaration */
  .replaceAll("(<)(\\w+:)(.*?>)", "$1$3") /* remove opening tag prefix */
  .replaceAll("(</)(\\w+:)(.*?>)", "$1$3"); /* remove closing tags prefix */
}
2 of 9
8

You can pre-process XML to remove all namespaces, if you absolutely must do so. I'd recommend against it, as removing namespaces from an XML document is in essence comparable to removing namespaces from a programming framework or library - you risk name clashes and lose the ability to differentiate between once-distinct elements. However, it's your funeral. ;-)

This XSLT transformation removes all namespaces from any XML document.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="node()">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*" />
    </xsl:copy>
  </xsl:template>

  <xsl:template match="*">
    <xsl:element name="{local-name()}">
      <xsl:apply-templates select="node()|@*" />
    </xsl:element>
  </xsl:template>

  <xsl:template match="@*">
    <xsl:attribute name="{local-name()}">
      <xsl:apply-templates select="node()|@*" />
    </xsl:attribute>
  </xsl:template>
</xsl:stylesheet>

Apply it to your XML document. Java examples for doing such a thing should be plenty, even on this site. The resulting document will be exactly of the same structure and layout, just without namespaces.

🌐
Kodejava
kodejava.org › how-do-i-remove-an-attribute-from-xml-element
How do I remove an attribute from XML element in JDOM? - Learn Java by Examples
May 24, 2023 - To remove an attribute you can call the removeAttribute(String name) method of the Element object. package org.kodejava.jdom; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; ...
🌐
Stack Overflow
stackoverflow.com › questions › 47458606 › java-how-to-remove-xmlns-from-dom-element
xml - Java: How to remove xmlns from DOM element? - Stack Overflow
November 23, 2017 - SupplementaryDataEnvelope1 supplementaryDataEnvelope1 = new SupplementaryDataEnvelope1(); //Adding SplmtryData DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); org.w3c.dom.Document doc = docBuilder.newDocument(); //doc.setDocumentURI("urn:iso:std:iso:20022:tech:xsd:camt.060.001.03"); Element sngtrStElement = doc.createElement("SngtrSt"); sngtrStElement.setTextContent(TranConstants.SNGTR_ST_VALUE); //sngtrStElement.removeAttributeNS("urn:iso:std:iso:20022:tech:xsd:camt.060.001.03", "xmlns"); supplementaryDataEnvelope1.setAny(sngtrStElement); ... <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.060.001.03"> <AcctRptgReq> ...
🌐
Stack Overflow
stackoverflow.com › questions › 34851280 › remove-xmlns-attribute
java - Remove xmlns attribute - Stack Overflow
January 18, 2016 - But xmlns:xsi attribute was NOT removed. Does anybody faced any similar issue or know how to approach this problem. ... 1. The XML you have shared is invalid, since the client tag isn't closed. 2. Can you please share your complete code? ... I am unable to reproduce your issue. It works as expected. ... xmlns:xsi is not an attribute.
🌐
GitHub
github.com › FasterXML › jackson-dataformat-xml › issues › 355
how to remove unnecessary xmlns="" in the child element · Issue #355 · FasterXML/jackson-dataformat-xml
August 13, 2019 - I want to remove the xmlns="" in the <name xmlns="">parent</name> and <Child xmlns=""> ... package utils; import java.io.IOException; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import com.ctc.wstx.stax.WstxInputFactory; import com.ctc.wstx.stax.WstxOutputFactory; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.dataformat.xml.XmlFactory; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty
Author   eonezhang
🌐
W3Schools
w3schools.com › xml › met_element_removeattributens.asp
XML DOM removeAttributeNS() Method
DOM Node Types DOM Node DOM NodeList DOM NamedNodeMap DOM Document DOM Element DOM Attribute DOM Text DOM CDATA DOM Comment DOM XMLHttpRequest DOM Parser XSLT Elements XSLT/XPath Functions ... The following code fragment loads "books_ns.xml" into xmlDoc and removes the "lang" attribute from the first <title> element:
Top answer
1 of 2
2

I found a solution to my problem. Posting it here if somebody lands here searching for an answer. I took a different approach. I let the CXF create the SOAP message and then I used the CXF custom interceptor to make changes to the message elements.

Configuration XML:

<!-- CXF Bus Configuration -->

<cxf:bus name="clientBus">
    <cxf:outInterceptors>
        <bean class="com.xxx.xxx.xxx.xxx.CustomMessageInterceptor" />
    </cxf:outInterceptors>
    <cxf:features>
        <cxf:logging/>
    </cxf:features>
</cxf:bus> 

CustomMessageInterceptor.java

package com.xxx.xxx.xxx.xxx;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;
import org.apache.cxf.binding.soap.interceptor.SoapPreProtocolOutInterceptor;
import org.apache.cxf.io.CachedOutputStream;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


@Component
public class CustomMessageInterceptor extends AbstractPhaseInterceptor<Message> {

    public CustomMessageInterceptor() {
        super(Phase.PRE_STREAM);
        addBefore(SoapPreProtocolOutInterceptor.class.getName());
    }

    private Logger log = LoggerFactory.getLogger(this.getClass());

    public void handleMessage(
            Message message) {

        OutputStream os = message.getContent(OutputStream.class);

        CachedStream cs = new CachedStream();
        message.setContent(OutputStream.class, cs);

        message.getInterceptorChain().doIntercept(message);

        try {
            cs.flush();
            IOUtils.closeQuietly(cs);
            CachedOutputStream csnew = (CachedOutputStream) message.getContent(OutputStream.class);

            String currentEnvelopeMessage = IOUtils.toString(csnew.getInputStream(), "UTF-8");
            csnew.flush();
            IOUtils.closeQuietly(csnew);

            if (log.isDebugEnabled()) {
                log.debug("Outbound message: " + currentEnvelopeMessage);
            }

            String res = changeOutboundMessage(currentEnvelopeMessage);
            if (res != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Outbound message has been changed: " + res);
                }
            }
            res = res != null ? res : currentEnvelopeMessage;

            InputStream replaceInStream = IOUtils.toInputStream(res, "UTF-8");

            IOUtils.copy(replaceInStream, os);
            replaceInStream.close();
            IOUtils.closeQuietly(replaceInStream);

            os.flush();
            message.setContent(OutputStream.class, os);
            IOUtils.closeQuietly(os);

        }
        catch (IOException ioe) {
            log.error("Unable to perform change.", ioe);
            throw new RuntimeException(ioe);
        }
    }

    protected String changeOutboundMessage(
            String currentEnvelope) {
        currentEnvelope = currentEnvelope.replace("<ClruInsert xmlns=\"\" xmlns:ns22=\"http://services/businessdomain/distributionmanagement/maintenance/maintenancerequestsresponses\">", "<ClruInsert>");
        currentEnvelope = currentEnvelope.replace("<BusinessTypeCd xmlns=\"\" xmlns:ns22=\"http://services/businessdomain/distributionmanagement/maintenance/maintenancerequestsresponses\"", "<BusinessTypeCd");

        return currentEnvelope;     
    }

    private class CachedStream extends CachedOutputStream {
        public CachedStream() {
            super();
        }
    }
}

It worked like a charm! :)

2 of 2
0

Change

Element businessTypeCode = document.createElement("BusinessTypeCd");

to

Element businessTypeCode = document.createElementNS(
  "http://services/businessdomain/distributionmanagement/maintenance/maintenancerequestsresponses", 
  "BusinessTypeCd");

and see https://docs.oracle.com/javase/8/docs/api/org/w3c/dom/Document.html#createElementNS-java.lang.String-java.lang.String- for more details.