Adding namespace to an already created XML document

后端 未结 3 1703
既然无缘
既然无缘 2020-12-01 22:00

I am creating a W3C Document object using a String value. Once I created the Document object, I want to add a namespace to the root element of this document. Here\'s my curr

3条回答
  •  星月不相逢
    2020-12-01 22:43

    Bellow approach also works for me, but probably should not use in performance critical case.

    1. Add name space to document root element as attribute.
    2. Transform the document to XML string. The purpose of this step is to make the child element in the XML string inherit parent element namespace.
    3. Now the xml string have name space.
    4. You can use the XML string to build a document again or used for JAXB unmarshal, etc.

    private static String addNamespaceToXml(InputStream in)
            throws ParserConfigurationException, SAXException, IOException,
            TransformerException {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        /*
         * Must not namespace aware, otherwise the generated XML string will
         * have wrong namespace
         */
        // dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.parse(in);
        Element documentElement = document.getDocumentElement();
        // Add name space to root element as attribute
        documentElement.setAttribute("xmlns", "http://you_name_space");
        String xml = transformXmlNodeToXmlString(documentElement);
        return xml;
    }
    
    private static String transformXmlNodeToXmlString(Node node)
            throws TransformerException {
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transformer = transFactory.newTransformer();
        StringWriter buffer = new StringWriter();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(new DOMSource(node), new StreamResult(buffer));
        String xml = buffer.toString();
        return xml;
    }
    

提交回复
热议问题