(Java) Mengedit File XML (DOM Parse)

Poshtingan Sebelumnya kita membaca kali ini kita akan mengedit file xml itu dengan java.

Buat File xml dengan nama file.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?><!--
    Document   : file.xml
    Created on : 21 Oktober 2012, 19:08
    Author     : mrroot
    Description:
        Purpose of the document follows.
--><company>
   <staff id="1">
	
	<lastname>Anna arthdi</lastname>
	<nickname>putra</nickname>
	<salary>9999</salary>
         <age>20</age>
         
         </staff>
</company>

Buat File Main dengan nama DOM_Parse_XML.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dom_parse_xml;

/**
 *
 * @author mrroot
 */
import java.io.File;
import java.io.IOException;
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.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DOM_Parse_XML {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
         try {
		String filepath = "/home/mrroot/NetBeansProjects/DOM_Parse_XML/src/dom_parse_xml/file.xml";
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
		Document doc = docBuilder.parse(filepath);
 
		// Get the root element
		Node company = doc.getFirstChild();
 
		// Get the staff element , it may not working if tag has spaces, or
		// whatever weird characters in front...it's better to use
		// getElementsByTagName() to get it directly.
		// Node staff = company.getFirstChild();
 
		// Get the staff element by tag name directly
		Node staff = doc.getElementsByTagName("staff").item(0);
 
		// update staff attribute
		NamedNodeMap attr = staff.getAttributes();
		Node nodeAttr = attr.getNamedItem("id");
		nodeAttr.setTextContent("2");
 
		// append a new node to staff
		Element age = doc.createElement("age");
		age.appendChild(doc.createTextNode("90"));
		staff.appendChild(age);
 
		// loop the staff child node
		NodeList list = staff.getChildNodes();
 
		for (int i = 0; i < list.getLength(); i++) {
 
                   Node node = list.item(i);
 
		   // get the salary element, and update the value
		   if ("salary".equals(node.getNodeName())) {
			node.setTextContent("88888");
		   }
 
                   //remove firstname
		   if ("firstname".equals(node.getNodeName())) {
			staff.removeChild(node);
		   }
 
		}
 
		// write the content into xml file
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(new File(filepath));
		transformer.transform(source, result);
 
		System.out.println("Done");
 
	   } catch (ParserConfigurationException pce) {
		pce.printStackTrace();
	   } catch (TransformerException tfe) {
		tfe.printStackTrace();
	   } catch (IOException ioe) {
		ioe.printStackTrace();
	   } catch (SAXException sae) {
		sae.printStackTrace();
	   }
	
    }
}

Jalankan dan file.xml di buka kembali maka akan ada perubahab

<?xml version="1.0" encoding="UTF-8" standalone="no"?><!--
    Document   : file.xml
    Created on : 21 Oktober 2012, 19:08
    Author     : mrroot
    Description:
        Purpose of the document follows.
--><company>
   <staff id="2">
	
	<lastname>Anna arthdi</lastname>
	<nickname>putra</nickname>
	<salary>8888</salary>
         <age>20</age>
         
         <age>90</age></staff>
</company>

Referensi :
http://www.mkyong.com/java/how-to-modify-xml-file-in-java-dom-parser/

Advertisements

Published by

jarcode

hello I am jarcode

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s