Java tutorial
//package com.java2s; /* This file is licensed to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** delimiter between node name and ns prefix ("xs:element") */ private static final char NAMESPACE_PREFIX = ':'; /** * Recursively strips the namespace information from a node. * @param node the starting node. * @param document host document * @return clean node */ public static Node removeNamespaceRecursive(final Node node, final Document document) { Node newNode = null; if (node.getNodeType() == Node.ELEMENT_NODE) { newNode = document.renameNode(node, null, removeNsPrefix(node.getNodeName())); } final NodeList list = node.getChildNodes(); for (int i = 0; i < list.getLength(); ++i) { removeNamespaceRecursive(list.item(i), document); } return newNode; } /** Strip the namespace prefix from node name, if any. this allows avoiding the Document strict validation error, that the node should not have prefix when it does not the have associated namespace. * @param nodeName name prefixed as ns:name * @return only 'name' part */ public static String removeNsPrefix(final String nodeName) { final int colonAt = nodeName.indexOf(NAMESPACE_PREFIX); if (colonAt >= 0) { return nodeName.substring(colonAt + 1, nodeName.length()); } return nodeName; } }