السلام عليكم..
مقدمه:
طلب منى أحد الأخوه مساعدته فى قراءة بيانات من ملف xml و من ثم كتابتها لقاعدة بيانات ...
قمت بكتابة هذا المثال بالإتصال بقاعدة بيانات MySQL .. (يمكنك الإتصال بأى قاعدة بيانات ترتاح لها )
المثال عباره عن ثلاث ملفات ... ملف ال XML ... و الذي سوف يتم قراءته و تخزينه لقاعدة البيانات ... و ملفان جافا..
نبدأ بملف ال XML :
<?xml version="1.0" encoding="UTF-8"?> <employees> <employee id="1"> <name>Ali</name> <age>20</age> </employee> <employee id="2"> <name>Mostafa</name> <age>30</age> </employee> <employee id="3"> <name>Wael</name> <age>23</age> </employee> </employees>
الملف الآخر هو الملف الذي سوف يمثل كائن من نوع Employee في الذاكره ..
/**
* represents an employee
* @author mhewedy
*
*/
public class Employee
{
int id;
String name;
double age;
public Employee() {
}
public Employee(int id, String name, double age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public double getAge() {
return age;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setAge(double age) {
this.age = age;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Employee [age=" + age + ", id=" + id + ", name=" + name + "]";
}
}و هذا هو الملف الثالث .. الذي يقوم بالقراء من ملف ال XML و الكتابه في قاعدة البيانات (التى بها الجدول مناسب)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Xml2DB
{
/////////////////////////////////////////////// JDBC /////////////////////////////////////////////////
private static Connection getConnection()
{
Connection conn = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "system");
} catch (Exception e)
{
e.printStackTrace();
}
return conn;
}
private static void insertEmployeeData(Connection conn, List<Employee> empList)
{
try {
PreparedStatement pstmt = conn.prepareStatement("insert into emp (id, name, age) values (?, ?, ?)");
for (Employee e : empList)
{
pstmt.setInt(1, e.getId());
pstmt.setString(2, e.getName());
pstmt.setDouble(3, e.getAge());
int ret = pstmt.executeUpdate();
if (ret == 1)
System.out.println("Employee ID=" + e.getId() + " inserted");
else
System.err.println("Error inserting Employee ID=" + e.getId());
}
} catch (SQLException e) {
e.printStackTrace();
}
}
//~~ JDBC
/////////////////////////////////////////////// XML /////////////////////////////////////////////////
private static List<Employee> getEmployeeListFromXMLFile()
{
List<Employee> empList = new ArrayList<Employee>();
try {
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(Xml2DB.class.getClassLoader().getResourceAsStream("employee.xml"));
NodeList list = doc.getDocumentElement().getChildNodes();
for (int i=0; i<list.getLength(); i++)
{
if (list.item(i).getNodeType() == Node.ELEMENT_NODE)
{
empList.add(node2Employee(list.item(i)));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return empList;
}
private static Employee node2Employee(Node empNode)
{
int id = Integer.parseInt(empNode.getAttributes().getNamedItem("id").getNodeValue());
String name = "";
double age = 0.0;
NodeList list = empNode.getChildNodes();
for (int i=0; i<list.getLength(); i++)
{
if (list.item(i).getNodeType() == Node.ELEMENT_NODE)
{
if ("name".equalsIgnoreCase(list.item(i).getNodeName()))
name = list.item(i).getFirstChild().getNodeValue();
if ("age".equalsIgnoreCase(list.item(i).getNodeName()))
{
try {
age = Double.parseDouble(list.item(i).getFirstChild().getNodeValue());
}catch(NumberFormatException ex) {
System.err.println("cannot age for employee ID: " + id);
}
}
}
}
return new Employee(id, name, age);
}
//~XML
public static void main(String[] args)
{
insertEmployeeData(getConnection(), getEmployeeListFromXMLFile());
}
}هذا هو كل شئ..