Hi Friend,
Try the following code:
<%@page import="java.io.*"%>
<%@page import=" org.w3c.dom.*"%>
<%@page import=" javax.xml.parsers.*"%>
<%@page import=" javax.xml.transform.*"%>
<%@page import=" javax.xml.transform.dom.*"%>
<%@page import=" javax.xml.transform.stream.*"%>
<%@page import=" java.sql.*"%>
<%!
public void createXmlTree(Document doc,String id,String name,String address,String contactNo) throws Exception {
Element root = doc.createElement("Employee");
doc.appendChild(root);
Element element1 = doc.createElement("Emp_ID");
root.appendChild(element1);
Text text1 = doc.createTextNode(id);
element1.appendChild(text1);
Element element2 = doc.createElement("Emp_Name");
root.appendChild(element2);
Text text2 = doc.createTextNode(name);
element2.appendChild(text2);
Element element3 = doc.createElement("Emp_Address");
root.appendChild(element3);
Text text3 = doc.createTextNode(address);
element3.appendChild(text3);
Element element4 = doc.createElement("Emp_ContactNo");
root.appendChild(element4);
Text text4 = doc.createTextNode(contactNo);
element4.appendChild(text4);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = sw.toString();
File file = new File("c:/employee.xml");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
bw.write(xmlString);
bw.flush();
bw.close();
}
%>
<%
response.setContentType("text/xml");
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:
mysql://localhost:3306/test","root";, "root");
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery("Select * from employee where emp_id='2'");
String id="", name="",address="",contactNo="";
while(rs.next()){
id=rs.getString("emp_id");
name=rs.getString("emp_name");
address=rs.getString("emp_address");
contactNo=rs.getString("contactNo");
}
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
createXmlTree(doc,id,name,address,contactNo);
out.println("<b>Xml File Created Successfully</b>");
}
catch(Exception e){}
%>
For more information,visit the following link:
http://www.roseindia.net/jsp/jsp-write-xml.shtmlThanks