代码之家  ›  专栏  ›  技术社区  ›  Farouk Alhassan

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

  •  3
  • Farouk Alhassan  · 技术社区  · 14 年前

    我想使用DOM api从下面的XML文档中移除包装器

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

    因此,我将只有这些作为最终输出:

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

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

    1 回复  |  直到 11 年前
        1
  •  4
  •   corriganjc    14 年前

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

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