본문 바로가기

Java

Java 와 xml 연동

package sample02;

import java.io.FileReader;


import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class mainClass {
	public static void main(String[] args) throws Exception{
		
		//client.xml java parsing
		Document xml = null;
		
		InputSource is = new InputSource(new FileReader("C:\\tmp\\client.xml"));
		
		xml = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
		
		//root element 취득
		Element element = xml.getDocumentElement();
		System.out.println(element.getTagName());
		
		//child node들을 취득
		NodeList list = element.getChildNodes();
		System.out.println(list.getLength());
		
		if(list.getLength() > 0) {	//child node 1개 이상
			for (int i = 0; i < list.getLength(); i++) {
				NodeList childList = list.item(i).getChildNodes();
				
				if(childList.getLength() > 0) {
					for(int j = 0; j <childList.getLength(); j++) {
						
						if(childList.item(j).getNodeName().equals("#text") == false){
							System.out.println("xml 태그명: " +  childList.item(j).getNodeName() +
									" xml값: " + childList.item(j).getTextContent());
						}
						
						
					}
				}
			}
		}
	}
}