Public/tip & tech

JAVA xml 파싱

quantapia 2012. 12. 10. 15:41

JAVA xml 파싱

import java.io.ByteArrayInputStream; 
import java.io.InputStream; 
import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 

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; 


public static void parsering(String xmlContents) throws Exception { 
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 

// XML DOM Parser를 생성 
DocumentBuilder parser = factory.newDocumentBuilder(); 

// XML 내용이 담긴 문자열을 InputStream으로 변환 
InputStream in = new ByteArrayInputStream(xmlContents.getBytes()); 

// XML 내용이 담긴 문자열을 읽어들여서 DOM을 구성 
Document doc = parser.parse(in); 

//Document doc = parser.parse("C:/test.xml"); 

// root Element 를 구한다. 
Element rootElement = doc.getDocumentElement(); 
System.out.println("########### rootElement.getTagName() : " + rootElement.getTagName()); 

// root Element의 모든 자식 노드를 구한다. 
NodeList memberList = rootElement.getChildNodes(); 

for(int i=0; iNode node = memberList.item(i); 

// 자식 노드가 요소일 경우에만 실행한다. 
if(node.getNodeType() == Node.ELEMENT_NODE) { 
System.out.println("########### node.getNodeName() : " + node.getNodeName()); // tag이름 

NodeList childNodeList = node.getChildNodes(); 

for(int k=0; kNode childNode = childNodeList.item(k); 

NamedNodeMap attrMap = childNode.getAttributes(); 
if(attrMap != null) { 
Node minNode = attrMap.getNamedItem("min"); 
Node maxNode = attrMap.getNamedItem("max"); 

// min Node가 있는경우 
if(minNode != null) { 
if(minNode != null && minNode.getNodeType() == Node.ATTRIBUTE_NODE) { 
System.out.println("##### min : Attribute Node"); 
} else if(minNode != null && minNode.getNodeType() == Node.ELEMENT_NODE) { 
System.out.println("##### min : Element Node"); 


System.out.println("##### min : " + minNode.getNodeValue()); 

// max Node가 있는경우 
if(maxNode != null) { 
System.out.println("##### max : " + maxNode.getNodeValue()); 



if(childNode.getNodeType() == Node.ELEMENT_NODE) { 
System.out.print("##### " + childNode.getNodeName()); 
System.out.print(" : "); 
System.out.println(childNode.getFirstChild().getNodeValue()); 




}