상세 컨텐츠

본문 제목

Java - XML 파싱 후 List로 출력하기

개발/Java

by 뉴에이스 2018. 10. 4. 13:12

본문

XML에 있는 데이터를 추출하는 방식 : 파싱 API
	
DOM(XML 정보 전체를 메모리에 로딩 후 접근, 메모리)
SAX(XML 정보를 한줄씩 로딩하여 처리(재로딩이 불가), 이벤트방식) - 빠른 속도, 메모리 효율 좋음
	
data/data.xml 파일을 읽어서 해당 내용을 화면에 출력

DOM 방식의 파싱을 처리하는 파서 객체를 얻기 (DocumentBuilder)
DocumentBuilder를 얻기 위해서는 DocumentBuilderFactory 클래스를 활용한다.
DocumentBuilderFactory는 추상 클래스로 객체 생성이 불가능
 

data.xml 소스

<?xml version="1.0" encoding="UTF-8"?>
<result>
	<family>
		<father>다스베이더</father>
		<mother>파드메</mother>
		<me>루크</me>
	</family>
	
	<family>
		<father>호머</father>
		<mother>마지</mother>
		<me>바트</me>
	</family>
	
	<family>
		<father>신영만</father>
		<mother>봉미선</mother>
		<me>짱구</me>
	</family>
</result>
 

Java 소스

public static void main(String[] args) {
	try {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder doc = factory.newDocumentBuilder();
		Document parser = doc.parse("data/data.xml"); // 파싱할 xml 파일 위치
		NodeList list = parser.getElementsByTagName("family");
		List<Family> fList = new ArrayList<>();

		for(int i=0 ; i<list.getLength() ; i++) {
			Node family = list.item(i);
			NodeList cList = family.getChildNodes();
			Family f = new Family();

			for(int k=0 ; k<cList.getLength() ; k++) {
				Node item = cList.item(k);
				String value = item.getNodeName();
				if(value.equals("#text")) continue;
				if(value.equals("father")) f.setFather(item.getTextContent());
				if(value.equals("mother")) f.setMother(item.getTextContent());
				if(value.equals("me")) f.setMe(item.getTextContent());
			}
			fList.add(f);
		}
		for(Family f : fList) {
			System.out.printf("%s, %s, %s\n", f.getFather(), f.getMother(), f.getMe() );
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
}

 

결과

다스베이더, 파드메, 루크
호머, 마지, 바트
신영만, 봉미선, 짱구

 

관련글 더보기

댓글 영역