Friday, September 11, 2015

Parsing XML using DOM (Basic)

Objectives

  1. Overview XML parse using DOM

  2. Create DOM with content loaded from SQL Server

  3. Save DOM to XML file

  4. Find information in XML file

  5. Update content in XML file




    1. Load Data form XML
      Create java class JavaApplication1 and declare 02 variable
      static ResultSet rs;
      static Document doc;

      Load Data from Employees table
      [sourcecode language="java"]
      Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
      Connection conn = DriverManager.getConnection("jdbc:sqlserver://"
      + "172.16.160.81\\sql2008;database=northwind;user=sa;password=sa;");
      PreparedStatement comm = conn.prepareStatement(""
      + "Select EmployeeID, FirstName,LastName From Employees");
      rs = comm.executeQuery();
      [/sourcecode]
      Create createDom method to transform RS to DOM
      [sourcecode language="java"]
      void createDom() {
      try {
      DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = fac.newDocumentBuilder();
      doc = db.newDocument();

      Element root = doc.createElement("emplist");
      // tao nut goc
      doc.appendChild(root);

      Comment comment = doc.createComment("danh sach nhan vien");
      // tao nut goc
      root.appendChild(comment);

      // doc du lieu va tao lai voi xml
      while (rs.next()) {
      // tao the emp
      Element emp = doc.createElement("emp");
      emp.setAttribute("status", "on");
      // the id
      Element id = doc.createElement("id");
      id.setTextContent(rs.getString("EmployeeID"));
      emp.appendChild(id);

      // the name
      Element name = doc.createElement("name");
      name.setTextContent(rs.getString("FirstName") + " " + rs.getString("LastName"));
      emp.appendChild(name);

      // gan vao root
      root.appendChild(emp);
      }
      Comment comment1 = doc.createComment("Nhan vien cuoi cung");
      // gan ghi chu vao phan tu cuoi cung
      root.insertBefore(comment1, root.getLastChild());
      } catch (Exception ex) {
      Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
      }
      }
      [/sourcecode]
      Write DOM to XML file
      [sourcecode language="java"]
      void writeToXML(String filename) {
      try {

      if(new File(filename).exists())
      {
      if(JOptionPane.showConfirmDialog(
      null, filename + " đ? t?n t?i ! \nB?n có mu?n ghi đè không?",
      "Xác nh?n!", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION)
      return;
      }

      // Create a DOM document for writing
      Source source = new DOMSource(doc);
      // Prepare the output file
      Result result = new StreamResult(filename);
      // Create an instance of Transformer
      Transformer xformer = TransformerFactory.newInstance().newTransformer();
      xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
      xformer.setOutputProperty(OutputKeys.INDENT, "yes");
      xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
      // Write the DOM document to the file
      xformer.transform(source, result);
      } catch (TransformerException ex) {
      System.out.println(ex.toString());
      }
      }
      [/sourcecode]
      Update status attribute of emp tag with content of id tag equal id
      [sourcecode language="java"]
      void deactive(int id) {
      // lay danh sach cac the con
      NodeList list = doc.getElementsByTagName("emp");
      // duyet qua ca the con
      for (int i = 0; i < list.getLength(); i++) {
      // tim con dau tien (the id) va kiem tra gia tri
      // neu bang voi id thi thuc hien
      if (Integer.parseInt(list.item(i).getFirstChild().getTextContent()) == id) {
      // cap nhat gia tri thuoc tinh status cua the emp
      list.item(i).getAttributes().getNamedItem("status").setNodeValue("off");
      break;
      }
      }
      }
      [/sourcecode]
      Find an employee in XML file with id tag content equal id
      [sourcecode language="java"]
      boolean exist(int id) {
      try {
      DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = fac.newDocumentBuilder();
      doc = db.parse(new File("src/emp.xml"));
      // lay danh sach cac the con
      NodeList list = doc.getElementsByTagName("id");
      // duyet qua ca the con
      for (int i = 0; i < list.getLength(); i++) {
      // tim con dau tien (the id) va kiem tra gia tri
      // neu bang voi id thi thuc hien
      if (Integer.parseInt(list.item(i).getTextContent()) == id) {
      return true;
      }
      }
      } catch (ParserConfigurationException ex) {
      Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
      } catch (SAXException ex) {
      Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
      } catch (IOException ex) {
      Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
      }

      return false;
      }
      [/sourcecode]
      Add new emp tag to existing XML file if emp id tag do not exist in XML file
      [sourcecode language="java"]
      void add(int newId, String newName) {
      try {
      DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = fac.newDocumentBuilder();
      doc = db.parse(new File("src/emp.xml"));

      if (exist(newId)) {
      JOptionPane.showMessageDialog(null, newId + " đ? t?n t?i !");
      return;
      }

      // lay the emplist
      Node root = doc.getDocumentElement();

      // tao the emp
      Element emp = doc.createElement("emp");
      emp.setAttribute("status", "on");
      // the id
      Element id = doc.createElement("id");
      id.setTextContent(newId + "");
      emp.appendChild(id);

      // the name
      Element name = doc.createElement("name");
      name.setTextContent(newName);
      emp.appendChild(name);

      // gan vao root
      root.appendChild(emp);

      } catch (ParserConfigurationException ex) {
      Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
      } catch (SAXException ex) {
      Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
      } catch (IOException ex) {
      Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
      }
      }
      [/sourcecode]
      Test app
      [sourcecode language="java"]
      public class JavaApplication1 {

      static ResultSet rs;
      static Document doc;

      /**
      * @param args the command line arguments
      */
      public static void main(String[] args) {
      try {
      Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
      Connection conn = DriverManager.getConnection("jdbc:sqlserver://"
      + "172.16.160.81\\sql2008;database=northwind;user=sa;password=sa;");
      PreparedStatement comm = conn.prepareStatement(""
      + "Select EmployeeID, FirstName,LastName From Employees");

      rs = comm.executeQuery();

      JavaApplication1 xmlDOM = new JavaApplication1();
      // tao doi tuong t? SQL Server
      xmlDOM.createDom();
      // ghi ra file
      xmlDOM.writeToXML("src/emp.xml");
      // cap nhat
      xmlDOM.deactive(5);
      // luu thay doi
      xmlDOM.writeToXML("src/emp.xml");
      // them node
      xmlDOM.add(100, "Nguyen Van Mit");
      // luu thay doi
      xmlDOM.writeToXML("src/emp.xml");

      } catch (Exception ex) {
      System.out.println(ex.toString());
      }
      }

      }
      [/sourcecode]

      }
      }

      Shifl + F6 to run
  • 1 comment:

    Translate