Get full xml text from Node instance

前端 未结 1 1176
梦毁少年i
梦毁少年i 2021-01-05 02:54

I have read XML file in Java with such code:

File file = new File(\"file.xml\");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentB         


        
相关标签:
1条回答
  • 2021-01-05 03:12

    Check out this other answer from stackoverflow.

    You would use a DOMSource (instead of the StreamSource), and pass your node in the constructor.

    Then you can transform the node into a String.

    Quick sample:

    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题