Alex Rivera | Logout

How do I remove namespaces from xml, using java dom?

Asked 2011-01-11T18:22:53.950
14

I have the following code

DocumentBuilderFactory dbFactory_ = DocumentBuilderFactory.newInstance();
Document doc_;
DocumentBuilder dBuilder = dbFactory_.newDocumentBuilder();
StringReader reader = new StringReader(s);
InputSource inputSource = new InputSource(reader);
doc_ = dBuilder.parse(inputSource);
doc_.getDocumentElement().normalize();

Then I can do

doc_.getDocumentElement();

and get my first element but the problem is instead of being job the element is tns:job.

I know about and have tried to use:

dbFactory_.setNamespaceAware(true);

but that is just not what I'm looking for, I need something to completely get rid of namespaces.

Any help would be appreciated, Thanks,

Josh

Edit
Report

3 Answers

7

For Element and Attribute nodes:

Node node = ...;
String name = node.getLocalName();

will give you the local part of the node's name.

See Node.getLocalName()

answered 2011-01-11T18:29:47.643
2

Tomalak, one fix of your XSLT (in 3rd template):

<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="@*">
    <!-- Here! -->
    <xsl:copy>
      <xsl:apply-templates select="node() | @*" />
    </xsl:copy>

  </xsl:template>
</xsl:stylesheet>
answered 2011-12-13T12:18:41.460
2
public static void wipeRootNamespaces(Document xml) {       
    Node root = xml.getDocumentElement();
    NodeList rootchildren = root.getChildNodes();
    Element newroot = xml.createElement(root.getNodeName());

    for (int i=0;i<rootchildren.getLength();i++) {
        newroot.appendChild(rootchildren.item(i).cloneNode(true));
    }

    xml.replaceChild(newroot, root);
}
answered 2013-05-14T19:42:01.817

Your Answer