Read Write File XML Menggunakan Java

 


Sebelum membuat code untuk membaca file XML, maka diperlukan library : dom-2.3.0-jaxb-1.0.6.jar. librari ini bisa di download pada link yang kemudian ditambahkan pada library pada proyek yang dibuat/

Berikut adalah cara read write XML dengan Java :

1. Read

1.1. Buat file XML : FileXML.xml

<?xml version="1.0"?>  

<class>  

    <student>  

        <id>101</id>  

        <firstname>Amir</firstname>  

        <lastname>Tan</lastname>  

        <subject>Matematika</subject>  

        <marks>85</marks>  

    </student>  

    <student>  

        <id>102</id>  

        <firstname>Junaidi</firstname>  

        <lastname>Lukman</lastname>  

        <subject>Biologi</subject>  

        <marks>70</marks>  

    </student>  

    <student>  

        <id>103</id>  

        <firstname>Budi</firstname>  

        <lastname>Santo</lastname>  

        <subject>English</subject>  

        <marks>80</marks>  

    </student>  

    <student>  

        <id>104</id>  

        <firstname>Mike</firstname>  

        <lastname>Irwan</lastname>  

        <subject>Fisika</subject>  

        <marks>75</marks>  

    </student>  

</class>  


1.2. Buat file baca dengan jawa : readxml.java

import javax.xml.parsers.DocumentBuilderFactory;  

import javax.xml.parsers.DocumentBuilder;  

import org.w3c.dom.Document;  

import org.w3c.dom.NodeList;  

import org.w3c.dom.Node;  

import org.w3c.dom.Element;  

import java.io.File;  

public class ReadXML  

{  

public static void main(String argv[])   

{  

try   

{  

//creating a constructor of file class and parsing an XML file  

File file = new File("D:\\FileXML.xml");  

//an instance of factory that gives a document builder  

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  

//an instance of builder to parse the specified xml file  

DocumentBuilder db = dbf.newDocumentBuilder();  

Document doc = db.parse(file);  

doc.getDocumentElement().normalize();  

System.out.println("Root element: " + doc.getDocumentElement().getNodeName());  

NodeList nodeList = doc.getElementsByTagName("student");  

// nodeList is not iterable, so we are using for loop  

for (int itr = 0; itr < nodeList.getLength(); itr++)   

{  

Node node = nodeList.item(itr);  

System.out.println("\nNode Name :" + node.getNodeName());  

if (node.getNodeType() == Node.ELEMENT_NODE)   

{  

Element eElement = (Element) node;  

System.out.println("Student id: "+ eElement.getElementsByTagName("id").item(0).getTextContent());  

System.out.println("First Name: "+ eElement.getElementsByTagName("firstname").item(0).getTextContent());  

System.out.println("Last Name: "+ eElement.getElementsByTagName("lastname").item(0).getTextContent());  

System.out.println("Subject: "+ eElement.getElementsByTagName("subject").item(0).getTextContent());  

System.out.println("Marks: "+ eElement.getElementsByTagName("marks").item(0).getTextContent());  

}  

}  

}   

catch (Exception e)   

{  

e.printStackTrace();  

}  

}  

}  


1.3. Hasil jika dijalankan :

Node Name: student

Student id: 101

First Name: Amir

Last Name: Tan

Subject: Matematika

Marks: 85


Node Name: student

Student id: 102

First Name: Junaidi

Last Name: Lukman

Subject: Biologi

Marks: 70


Node Name: student

Student id: 103

First Name: Budi

Last Name: Santo

Subject: English

Marks: 80


Node Name: student

Student id: 104

First Name: Mike

Last Name: Irwan

Subject: Fisika

Marks: 75



2. Write

2.1. Buat file jawa untuk menulis : writexml.java

import java.io.File;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.ParserConfigurationException;

import javax.xml.transform.Transformer;

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.Attr;

import org.w3c.dom.Document;

import org.w3c.dom.Element;

 

public class CreateXML {

 

    public static final String xmlFilePath = "D:\\\XMLfile.xml";

 

    public static void main(String argv[]) {

        try {

            DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();

            DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();

            Document document = documentBuilder.newDocument();

            // root element

            Element root = document.createElement("company");

            document.appendChild(root);

            // employee element

            Element employee = document.createElement("employee");

            root.appendChild(employee);

            // set an attribute to staff element

            Attr attr = document.createAttribute("id");

            attr.setValue("10");

            employee.setAttributeNode(attr);

            //you can also use staff.setAttribute("id", "1") for this

            // firstname element

            Element firstName = document.createElement("firstname");

            firstName.appendChild(document.createTextNode("Amir"));

            employee.appendChild(firstName);

            // lastname element

            Element lastname = document.createElement("lastname");

            lastname.appendChild(document.createTextNode("Tan"));

            employee.appendChild(lastname);

            // email element

            Element email = document.createElement("email");

            email.appendChild(document.createTextNode("amir@gmail.com"));

            employee.appendChild(email);

            // department elements

            Element department = document.createElement("department");

            department.appendChild(document.createTextNode("Student"));

            employee.appendChild(department);

            // create the xml file

            //transform the DOM Object to an XML File

            TransformerFactory transformerFactory = TransformerFactory.newInstance();

            Transformer transformer = transformerFactory.newTransformer();

            DOMSource domSource = new DOMSource(document);

            StreamResult streamResult = new StreamResult(new File(xmlFilePath));

            // If you use

            // StreamResult result = new StreamResult(System.out);

            // the output will be pushed to the standard output ...

            // You can use that for debugging 

            transformer.transform(domSource, streamResult);

            System.out.println("Done creating XML File");

        } catch (ParserConfigurationException pce) {

            pce.printStackTrace();

        } catch (TransformerException tfe) {

            tfe.printStackTrace();

        }

    }

}


2.2. Hasil File XML ; XMLFile.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<company>

<employee id="10">

<firstname>Amir</firstname>

<lastname>Tan</lastname>

<email>amir@gmail.com</email>

<department>Studeint</department>

</employee>

</company>