简体   繁体   中英

Read XML from InputStreamReader and write it to file

My code receives an XML String from an InputStreamReader (it's actually the output of REST request to another server) and then the String is written to a file (file includes not only XML ).

The problem is that the String is received as one line of XML and so it's stored as one huge line in the file (no indentation, tabs, formatting etc.).

Can I receive this XML stream and format it while writing it to the file?

Note: I can't use DOM here, it must be implemented without loading the XML to memory.

You can do it using Transformer and SAX , if you are allowed to :-

public static void prettyPrintXmlToFile(String sourceXml, File targetFile) throws Exception{
    Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    Source xmlSource = new SAXSource(new InputSource(new StringReader(sourceXml)));
    StreamResult res = new StreamResult(targetFile);
    serializer.transform(xmlSource, res);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM