(Java) Membaca File XML – (DOM Parse)

Kemarin sudah mengkonfesi java ke xml sekarang kita akan membaca count dengan menggunakan element .

Create File XML dengan nama file.xml

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

<;!--
    Document   : file.xml
    Created on : 21 Oktober 2012, 19:20
    Author     : mrroot
    Description:
        Purpose of the document follows.
-->

<;company>
	<;staff id="1">
		<;firstname>Anna Arthdi<;/firstname>
		<;lastname>Putra<;/lastname>
		<;nickname>Aerdy<;/nickname>
		<;salary>999999999<;/salary>
		<;age>20<;/age>
	<;/staff>
	<;staff id="2">
		<;firstname>Anna<;/firstname>
		<;lastname>Erdiawan<;/lastname>
		<;nickname>wawan<;/nickname>
		<;salary>99999999999<;/salary>
                <;age>23<;/age>
	<;/staff>
	<;staff id="3">
		<;firstname>Ryan<;/firstname>
		<;lastname>riyadi<;/lastname>
		<;nickname>Ryan<;/nickname>
		<;salary>99999<;/salary>
		<;age>15<;/age>
	<;/staff>
<;/company>

Create File Main java dengan nama DOM_Count_XML.java

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

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author mrroot
 */
public class DOM_Count_XML {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        
        try {
                //alamat path file .xml yang akan di baca
		String filepath = "/home/mrroot/NetBeansProjects/DOM_Count_XML/src/dom_count_xml/file.xml";
                
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
		Document doc = docBuilder.parse(filepath);
 
		NodeList list = doc.getElementsByTagName("staff");
 
		System.out.println("Total Semua Element " + list.getLength());
 
	} catch (ParserConfigurationException pce) {
		pce.printStackTrace();
	} catch (IOException ioe) {
		ioe.printStackTrace();
	} catch (SAXException sae) {
		sae.printStackTrace();
	}
  }
}

Run Dan Hasil nya akan seperti dibawah ini

Referensi :

http://www.mkyong.com/java/how-to-count-xml-elements-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