09 November 2016

XML DOM: CRUD Create Update Delete XML NetBeans

student.xml
Java XML 2016
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<student>

    <student>
        <id>std1</id>
        <name>Name 1</name>
        <age>20</age>
    </student>
    <student>
        <id>std2</id>
        <name>Name 2</name>
        <age>20</age>
    </student>
    
</student>
Main.java
Java XML 2016
package dom;

/**
 *
 * @author Lonely
 */
public class Main {
    public static void main(String[] args) {
        StudentDOM sd = new StudentDOM();
        sd.Add();
        //sd.delete("st4");
        //sd.update("st4", "Antonio", 25);
    }
}
DomHelper.java
Java XML 2016

package dom;

import java.io.StringWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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;
import org.w3c.dom.Document;

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

    public static Document getDocument(String path_to_file) {
        Document d = null;
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            d = db.parse(path_to_file);
        } catch (Exception ex) {
            return d = null;
        }
        return d;
    }

    public static String getXMLContent(Document d) throws TransformerException {
        String result = null;
        try {
            TransformerFactory tff = TransformerFactory.newInstance();
            Transformer tf = tff.newTransformer();
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            StringWriter sw = new StringWriter();
            StreamResult rs = new StreamResult(sw);
            DOMSource source = new DOMSource();
            tf.transform(source, rs);
            result = sw.toString();
        } catch (TransformerConfigurationException ex) {
            result = null;
        }
        return result;
    }

    public static void saveXMLContent(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());
        }
    }
}
StudentDOM.java
Java XML 2016

package dom;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

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

    public void Add() {
        Document d;
        try {
            d = DomHelper.getDocument("src\\data\\student.xml");
            Element students = d.getDocumentElement();
            Element student = d.createElement("student");
            Element id = d.createElement("id");
            id.appendChild(d.createTextNode("st4"));
            student.appendChild(id);
            //Create name tag
            Element name = d.createElement("name");
            name.appendChild(d.createTextNode("name 4"));
            student.appendChild(name);
            //Create age tag
            Element age = d.createElement("age");
            age.appendChild(d.createTextNode("25"));
            student.appendChild(age);

            students.appendChild(student);
            //Write to file
            DomHelper.saveXMLContent(d, "src\\data\\student.xml");

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public void delete(String id) {
        Document d;
        try {
            d = DomHelper.getDocument("src\\data\\student.xml");
            NodeList nl = d.getElementsByTagName("student");
            for (int i = 0; i < nl.getLength(); i++) {
                Element sStudent = (Element) nl.item(i);
                if (sStudent.getElementsByTagName("id").item(0).getTextContent().equals(id)) {
                    sStudent.getParentNode().removeChild(sStudent);
                }
            }
            //Write to file
            DomHelper.saveXMLContent(d, "src\\data\\student.xml");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public void update(String id, String name, int age) {
        Document d;
        try {
            d = DomHelper.getDocument("src\\data\\student.xml");
            NodeList nl = d.getElementsByTagName("student");
            for (int i = 0; i < nl.getLength(); i++) {
                Element sStudent = (Element) nl.item(i);
                if (sStudent.getElementsByTagName("id").item(0).getTextContent().equals(id)) {
                    sStudent.getElementsByTagName("name").item(0).setTextContent(name);
                    sStudent.getElementsByTagName("age").item(0).setTextContent(String.valueOf(age));
                }
            }
            //Write to file
            DomHelper.saveXMLContent(d, "src\\data\\student.xml");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
Crud Basic
  • Add new xml


  • XML được tạo


  •  Update xml


  •  XML đã được update


  •  Xóa xml

  • Xóa thành công xml

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang