package com.server;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
public class XmlServlet extends HttpServlet
{
Connection con=null;
Statement st=null;
ResultSet rs = null;
String xmlString ;
BufferedWriter bw;
Document doc;
String g,g1,g2;
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e)
{
System.out.println("mona"+e.getMessage());
}
try{
// con = DriverManager.getConnection("jdbc:mysql://localhost:3306/popup","root","enggheads");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/enggheads","root","enggheads");
st = con.createStatement();
}
catch(SQLException e)
{
System.out.println("mona1"+e.toString());
}
try
{
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("C:/roseindia.xml"));
doc.getDocumentElement ().normalize ();
System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());
NodeList listOfPersons = doc.getElementsByTagName("employee");
for(int s=0; s<listOfPersons.getLength() ; s++){
Node firstPersonNode = listOfPersons.item(s);
if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
Element firstPersonElement = (Element)firstPersonNode;
NodeList firstNameList = firstPersonElement.getElementsByTagName("name");
Element firstNameElement = (Element)firstNameList.item(0);
NodeList textFNList = firstNameElement.getChildNodes();
String name= ((Node)textFNList.item(0)).getNodeValue().trim();
NodeList lastNameList = firstPersonElement.getElementsByTagName("address");
Element lastNameElement = (Element)lastNameList.item(0);
NodeList textLNList = lastNameElement.getChildNodes();
String address= ((Node)textLNList.item(0)).getNodeValue().trim();
int i=st.executeUpdate("insert into data(name,address) values('"+name+"','"+address+"')");
}
}
System.out.println("Data is successfully inserted!");
}
catch (Exception err) {
System.out.println(" " + err.getMessage ());
}
}}
XML FILE ( roseindia.xml )
<?xml version="1.0" encoding="utf-8"?>
<countries>
<employee>
<name>Norway</name>
<address>N</address>
</employee>
<employee>
<name>Sweden</name>
<address>S</address>
</employee>
<employee>
<name>France</name>
<address>F</address>
</employee>
<employee>
<name>Italy</name>
<address>I</address>
</employee>
</countries>
No comments:
Post a Comment