[Java] xml 파싱 예제

프로그래밍/JAVA 2020. 7. 11. 20:37 posted by 야매코더

xml data 

더보기

<?xml version="1.0" encoding="UTF-8"?>
<members>
  <member>
    <number>1</number>
    <name>홍길동</name>
    <address>서울시</address>
    <join>2020/05/12</join>
  </member>
  <member>
    <number>2</number>
    <name>일지매</name>
    <address>부산시</address>
    <join>2020/04/03</join>
  </member>
  <member>
    <number>3</number>
    <name>임꺽정</name>
    <address>광주시</address>
    <join>2020/06/22</join>
  </member>
</members>

java 샘플 소스 

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 test01 {

	public static void main(String[] args) {
		Document xml = null;
		
		try {			
			InputSource is = new InputSource(new FileReader("data\\data.xml"));
			xml = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
			// root element
			Element element = xml.getDocumentElement();
			// child node
			NodeList list = element.getChildNodes();
			// child node
			if (list.getLength() > 0) {
				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("tag : " + childList.item(j).getNodeName() + ", xml Value : "
										+ childList.item(j).getTextContent());
							}
						}
					}
					System.out.println();
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
반응형