从Node实例获取完整的xml文本

xVi*_*Vir 8 java xml

我用Java读取了这个代码的XML文件:

File file = new File("file.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);

NodeList nodeLst = doc.getElementsByTagName("record");

for (int i = 0; i < nodeLst.getLength(); i++) {
     Node node = nodeLst.item(i);
...
}
Run Code Online (Sandbox Code Playgroud)

那么,我如何从节点实例中获取完整的xml内容?(包括所有标签,属性等)

谢谢.

Pau*_*ime 14

从stackoverflow中查看其他答案.

您将使用DOMSource(而不是StreamSource),并在构造函数中传递您的节点.

然后,您可以将节点转换为String.

快速样品:

public class NodeToString {
    public static void main(String[] args) throws TransformerException, ParserConfigurationException, SAXException, IOException {
        // just to get access to a Node
        String fakeXml = "<!-- Document comment -->\n    <aaa>\n\n<bbb/>    \n<ccc/></aaa>";
        DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = docBuilder.parse(new InputSource(new StringReader(fakeXml)));
        Node node = doc.getDocumentElement();

        // test the method
        System.out.println(node2String(node));
    }

    static String node2String(Node node) throws TransformerFactoryConfigurationError, TransformerException {
        // you may prefer to use single instances of Transformer, and
        // StringWriter rather than create each time. That would be up to your
        // judgement and whether your app is single threaded etc
        StreamResult xmlOutput = new StreamResult(new StringWriter());
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(new DOMSource(node), xmlOutput);
        return xmlOutput.getWriter().toString();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 多么可怕的Api! (4认同)