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

Far*_*san 3 java xml dom

我想使用 DOM api 从以下 XML 文档中删除包装器

<hs:PageWrapper>
    <div id="botton1"/>
    <div id="botton2"/>
</hs:PageWrapper>
Run Code Online (Sandbox Code Playgroud)

这样我只会将这些作为最终输出:

<div id="botton1"/>
<div id="botton2"/>
Run Code Online (Sandbox Code Playgroud)

我怎样才能在Java中做到这一点?

cor*_*njc 5

您想要做的不会产生格式良好的 XML,因为文档根目录中有 2 个元素。但是,执行您想要的操作的代码如下。它获取包装元素的子节点,为每个节点创建一个新文档,将节点导入到文档中并将文档写入字符串中。

    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);
}
Run Code Online (Sandbox Code Playgroud)