Sunday, November 23, 2008

parsing xml di java pakai dom

import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;

public class NodeExplorer{
public static void main(String[] args) {
try{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
//System.out.print("Enter xml file name: ");
String str = "test.xml";
File file = new File(str);
if (file.exists()){
DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = fact.newDocumentBuilder();
Document doc = builder.parse(str);
Node node = doc.getDocumentElement();
String root = node.getNodeName();
System.out.println("Root Node: " + root);

nodeExplorer(node);

}
else{
System.out.println("File not found!");
}
}
catch(Exception e){}
}


public static void nodeExplorer(Node node)
{
NodeList nodeList = node.getChildNodes();

int length = nodeList.getLength();

if(length>0)
{
for(int i=0;i<length;i++)
{
Node curr = nodeList.item(i);
System.out.println(curr.getNodeName());
nodeExplorer(curr);
}
}
else
{
System.out.println("mentok");
}
}
}

4 comments:

  1. SAX lebih cepet.

    Kalo cuma buat bikin konfigurasi, xerces overkill. Pake Simple aja.

    ReplyDelete
  2. iya sih lebih cepet, tapi kodingnya ribet karena dia main event base

    ReplyDelete
  3. Mas gimana ya caranya mendapatkan nilai seluruh attribute yang sama dalam xml, contohnya seperti ini http://www.kaskus.us/showthread.php?t=4768294

    ReplyDelete