Thursday, November 10, 2011

Convert XML file To String object

The following code will read the XML from file specified as method argument, and will return the String object containing the XML file contents, null otherwise.

public static String convertXMLFileToString(String filePath) {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
InputStream inputStream = new FileInputStream(new File(filePath));
org.w3c.dom.Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream);
StringWriter stwriter = new StringWriter();
Transformer serializer = TransformerFactory.newInstance().newTransformer();
serializer.transform(new DOMSource(document), new StreamResult(stwriter));
return stwriter.toString();
} catch (Exception e) {
return null;