
Hi Friends,
I had an requirement in which a java program receives an xml messages from external web application such as (jsp, php) and then it converts the received xml message into a string.
could some one suggest how can I go about it or could some one provide me with sample code so that I can study from it.
Thanks in advance.
Regards, Lisha Ahuja

Hi,
You can use the Transformer class:
Transformer tFormer = TransformerFactory.newInstance().newTransformer();
For transforming the Document object into string.
XML file:
<?xml version = "1.0" ?>
<accounts>
<account>
<id>454457858778</id>
<name>Dinesh</name>
</account>
</accounts>
Java code:
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
public class XMLtoString{
static public void main(String[] args){
try{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("1.xml");
StringWriter stringWriter = new StringWriter();
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(new DOMSource(doc), new StreamResult(stringWriter));
String strFileContent = stringWriter.toString(); //This is string data of xml file
System.out.println(strFileContent);
}
catch (Exception e){
e.getMessage();
}
}
}
Thanks
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.