Monday, February 9, 2009

Convert XML to String

/**
* This method is used to convert XML file To String using DOMParser
* @author jijo
* @param xMLFile
* @return
*/
public static String convertXMLToString(String xMLFile){
String xmlString = null;
DOMParser parser = new DOMParser();
try{
parser.parse(xMLFile);
Document doc = parser.getDocument();
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
xmlString = writer.toString();
}
catch (Exception e) {
logger.info("StringUtils:convertXMLToString:Filename : "+xMLFile);
logger.error("StringUtils:convertXMLToString:"+e);
}
return xmlString;
}





/**
* This method is used to convert XML file To String using Document
* @author jijo
* @param xMLFile
* @return
*/

public static String xmlToString(String path) throws ParserConfigurationException, SAXException
{
String s = null;
try
{
//String xmlFile = "F://xml//ThuJan2915_10_572009.xml";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File(path));
Element root = doc.getDocumentElement();
s = root.toString();
//System.out.println(s);
}
catch(IOException e)
{ e.printStackTrace();
}

return s;
}

No comments: