如何使用DOM删除XML文档的根节点 [英] How to remove the root node of an XML document with DOM

查看:141
本文介绍了如何使用DOM删除XML文档的根节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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"/>
<div id="botton2"/>

我如何在Java中执行此操作?

How can i do this in Java?

推荐答案

你想做的不会导致格式良好的XML,因为在文档根目录下将有2个元素。但是,您要做的代码如下所示。它获取包装器元素的子节点,为每个节点创建一个新文档,将节点导入到文档中,并将该文档写入一个String。

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);
}

这篇关于如何使用DOM删除XML文档的根节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆