Remove namespace from XML in Java

前端 未结 2 418
不思量自难忘°
不思量自难忘° 2021-01-05 05:55

I want to remove namespace from XML in Java. Can you pls guide on what needs to be done. Can use DOM parser but that would be a node by node parsing. I want to know if there

2条回答
  •  抹茶落季
    2021-01-05 06:35

    Regex can be used for more information refer this

    public static string RemoveAllXmlNamespace(string xmlData)
            {
                string xmlnsPattern = "\\s+xmlns\\s*(:\\w)?\\s*=\\s*\\\"(?[^\\\"]*)\\\"";
                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 null 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);
            }
        }
    

提交回复
热议问题