convert xml document to string

Discussions

XML & Web services: convert xml document to string

  1. convert xml document to string (1 messages)

    Hi,

    I have a piece of code (patched together from various books and web tutorials) that will take the contents of an XML document (created with DOM and database pulls) and write it out to System.out or a file. I'm trying to extend it so it can write out the contents to a string. Here's the code that works (writing to System.out)...

    File file = new File("C:/JavaWork/sec4mapping/output.xml");
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            
            DOMSource source = new DOMSource(doc);
            Result output = new StreamResult(System.out);
            
            System.out.println("Creating xml file");
            transformer.transform(source, output);

    Anyone know how to alter this so that the output goes to a string? source.toString() doesn't output the contents of the file, unfortunately.

    Thanks for the help,
    Geoff
  2. convert xml document to string[ Go to top ]

    Im assuming StreamResult is accepting an OutputStream object...

    Replace System.out with an object of type java.io.ByteArrayOutputStream

    Then call to String on that object.

    http://java.sun.com/j2se/1.4/docs/api/java/io/ByteArrayOutputStream.html