8

I have read XML file in Java with such code:

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

So, how I can get full xml content from node instance? (including all tags, attributes etc.)

Thanks.

xVir
  • 545
  • 1
  • 12
  • 21
  • 1
    What do you mean by "get full xml content"? What type of object are you expecting to get back? A String? Something else? – Jim Garrison Sep 04 '11 at 14:37
  • The full xml content will be in file.xml, or am I missing the point? Otherwise try http://stackoverflow.com/questions/35785/xml-serialization-in-java or http://xstream.codehaus.org/tutorial.html. – Paul Grime Sep 04 '11 at 17:08
  • @PaulGrime, have you mean, what I must serialize "node" instance with XML serializer? – xVir Sep 04 '11 at 17:24
  • @JimGarrison, by "get full xml content" I mean next (for example): data data data – xVir Sep 04 '11 at 17:28

1 Answers1

14

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();
    }
}
Community
  • 1
  • 1
Paul Grime
  • 14,970
  • 4
  • 36
  • 58