15 November 2016

XML DOM: Lấy dữ liệu từ Database để Tạo file XML NetBeans Mysql Workbench


Database

Create database xml;

Create table products;

question_1
Document_DOM.java
Java XML 2016
package controller;

import javax.xml.parsers.*;
import org.w3c.dom.Document;

/**
 *
 * @author Lonely
 */
public class Document_DOM {

    public static Document getDocumentNew() {
        Document d = null;
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            d = db.newDocument();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return d;
    }
}
SaveXML.java
Java XML 2016
package controller;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

/**
 *
 * @author Lonely
 */
public class SaveXML {

    public static void saveXMLContent(org.w3c.dom.Document d, String path_to_file) throws TransformerException {
        try {
            TransformerFactory tff = TransformerFactory.newInstance();
            Transformer tf = tff.newTransformer();
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            DOMSource source = new DOMSource(d);
            StreamResult rs = new StreamResult(path_to_file);
            tf.transform(source, rs);
        } catch (TransformerConfigurationException ex) {
            System.out.println(ex.getMessage());
        }
    }
}
CreateXML.java
Java XML 2016
package question_1;

import controller.SaveXML;
import java.util.List;
import org.w3c.dom.*;

/**
 *
 * @author Lonely
 */
public class CreateXML {

    List<product> list = new GetProductData().getList();

    public void create() {
        try {
            Document doc = controller.Document_DOM.getDocumentNew();
            // root element
            Element rootElement = doc.createElement("products");
            doc.appendChild(rootElement);

            for (int i = 0; i < list.size(); i++) {
                //  product element
                Element product = doc.createElement("product");
                rootElement.appendChild(product);

                // setting attribute to element
                Attr attr = doc.createAttribute("id");
                attr.setValue(Integer.toString(list.get(i).getId()));
                product.setAttributeNode(attr);

                // product element
                Element name = doc.createElement("name");
                name.appendChild(doc.createTextNode(list.get(i).getName()));
                product.appendChild(name);

                // product element
                Element des = doc.createElement("des");
                des.appendChild(doc.createTextNode(list.get(i).getDes()));
                product.appendChild(des);

                // product element
                Element price = doc.createElement("price");
                price.appendChild(doc.createTextNode(list.get(i).getPrice()));
                product.appendChild(price);

                // product element
                Element catalog = doc.createElement("catalog");
                catalog.appendChild(doc.createTextNode(list.get(i).getCatalog()));
                product.appendChild(catalog);

                // write the content into xml file
                SaveXML.saveXMLContent(doc, "src\\Data\\products.xml");
            }
            System.out.println("===QUESTION [1] Create product thanh cong!");
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}
DBUtil.java
Java XML 2016
package question_1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 *
 * @author Lonely
 */
public class DBUtil {

    private static Connection connection = null;

    public static Connection getConnection() {
        if (connection != null) {
            return connection;
        } else {
            try {
                Class.forName("com.mysql.jdbc.Driver");
                connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/xml", "root", "1234567");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return connection;
        }
    }

    //Test connection

//    public static void main(String[] args) {
//        System.out.println(getConnection());
//    }
}
GetProductData.java
Java XML 2016
package question_1;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Lonely
 */
public class GetProductData {

    public List<product> getList() {
        List<product> list = new ArrayList();
        try {
            product p = null;
            String sql = "Select * from products";
            Connection conn = DBUtil.getConnection();
            PreparedStatement stmt = conn.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                p = new product(rs.getInt(1),rs.getString(2) ,rs.getString(3), rs.getString(4), rs.getString(5));
                list.add(p);
            }
            return list;
        } catch (SQLException ex) {
            Logger.getLogger(GetProductData.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

}
product.java
Java XML 2016
package question_1;

/**
 *
 * @author Lonely
 */
public class product {

    private int id;
    private String name;
    private String des;
    private String price;
    private String catalog;

    public product(int id, String name, String des, String price, String catalog) {
        this.id = id;
        this.name = name;
        this.des = des;
        this.price = price;
        this.catalog = catalog;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
    

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDes() {
        return des;
    }

    public void setDes(String des) {
        this.des = des;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getCatalog() {
        return catalog;
    }

    public void setCatalog(String catalog) {
        this.catalog = catalog;
    }

}
Run test:  Main.java
Java XML 2016
package run;

import question_1.CreateXML;

public class Main {

    public static void main(String[] args) {
        //1 Tạo file XML dùng DOM 
        CreateXML c = new CreateXML();
        c.create();
    }
}
Run test
Tạo thành công file products.xml

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang