如何使用DOM删除XML文档的根节点

时间:2010-11-16 21:06:55

标签: java xml dom

我想使用DOM api

从以下XML文档中删除包装器
<hs:PageWrapper>
    <div id="botton1"/>
    <div id="botton2"/>
</hs:PageWrapper>

所以我只将这些作为最终输出:

<div id="botton1"/>
<div id="botton2"/>

我如何用Java做到这一点?

1 个答案:

答案 0 :(得分:4)

您要做的事情不会产生格式良好的XML,因为文档根目录中会有2个元素。但是,下面是代码来执行您想要的操作。它获取包装元素的子节点,为每个节点创建一个新文档,将节点导入文档并将文档写入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);
}