开发者

How to remove the root node of an XML document with DOM

I want to remove the wrapper from the following XML document using the DOM api

<hs:PageWrapper>
    <div id="botton1"/>
    <div id="botton2"/>
</hs:PageWrapper>

so that I will only have these as the final output:

<div id="botton1"/>
&开发者_运维知识库lt;div id="botton2"/>

How can i do this in Java?


What you want to do will not result in well formed XML as there will be 2 elements at the document root. However, code to do what you want is below. It gets the child nodes of the wrapper element, creates a new document for each node, imports the node into the document and writes the document into a String.

    public String peel(String xmlString) {
    StringWriter writer = new StringWriter();
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new InputSource(new StringReader(
                xmlString)));
        NodeList nodes = document.getDocumentElement().getChildNodes();
        for (int i = 0; i < nodes.getLength(); i++) {
            Node n = nodes.item(i);
            Document d = builder.newDocument();
            Node newNode = d.importNode(n, true);
            d.insertBefore(newNode, null);
            writeOutDOM(d, writer);
        }
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (TransformerFactoryConfigurationError e) {
        e.printStackTrace();
    } catch (TransformerException e) {
        e.printStackTrace();
    }
    return writer.toString();
}

protected void writeOutDOM(Document doc, Writer writer) 
     throws TransformerFactoryConfigurationError, TransformerException {
    Result result = new StreamResult(writer);
    DOMSource domSource = new DOMSource(doc);
    Transformer transformer = TransformerFactory.newInstance()
            .newTransformer();
    transformer.setOutputProperty("omit-xml-declaration", "yes");
    transformer.transform(domSource, result);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜