I had to find out a way to read an XML file, and convert it to java String. Below is the code snippet I used.
public String convertXMLFileToString(String fileName)
{
try{
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
InputStream inputStream = new FileInputStream(new File(fileName));
org.w3c.dom.Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputStream);
StringWriter stw = new StringWriter();
Transformer serializer = TransformerFactory.newInstance().newTransformer();
serializer.transform(new DOMSource(doc), new StreamResult(stw));
return stw.toString();
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
You code is really helpful to me. Thank you very much.
ReplyDeleteSuresh
Hai what if i want to convert xml string to xml file
ReplyDeletejust write it to file with .xml extension.. if you want to format it, then am not sure hw to do it..
ReplyDeletethanks
ReplyDeleteit helped me a lot
Thanks for the posting.. Sun should just make a simple class to do this.
ReplyDeleteThanks a lot
ReplyDeleteHi nice code......
ReplyDeleteIt helped me
Straight and to the point. Thanks for sharing
ReplyDeleteThank you so much. This is just awesome.
ReplyDeleteAnd this can simply be put in any class and it will function properly?
ReplyDeleteyes
ReplyDeleteThank you so much!! :)
ReplyDeleteFANTASTIC!! Thank you!
ReplyDeleteYaaa, Nice Man thanks a lot - Ramas
ReplyDeleteI get this error below, can you please help.
ReplyDeleteException in thread "main" java.lang.AbstractMethodError: org.apache.xerces.dom.DeferredDocumentImpl.getXmlStandalone()Z
at com.sun.org.apache.xalan.internal.xsltc.trax.DOM2TO.setDocumentInfo(DOM2TO.java:373)
at com.sun.org.apache.xalan.internal.xsltc.trax.DOM2TO.parse(DOM2TO.java:127)
at com.sun.org.apache.xalan.internal.xsltc.trax.DOM2TO.parse(DOM2TO.java:94)
at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transformIdentity(TransformerImpl.java:661)
at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:707)
at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:313)
at
Very helpfull code! Thank you soo much!
ReplyDeleteGreat work! This code is very helpful!! Thank U!
ReplyDeleteVery helpfull..Thank you very much!
ReplyDeletegood
ReplyDeletevery helpful. thanks
ReplyDeletethanks a lot dude.....
ReplyDeletethanks very much. this helped just in time.
ReplyDelete