'XML'에 해당되는 글 2건

  1. 2017.04.19 [Java] XStream을 사용한 XML 파싱
  2. 2017.04.18 [Java] XPath를 활용한 XML 파싱
2017. 4. 19. 07:56

[Java] XStream을 사용한 XML 파싱




XStream 라이브러리를 사용하여 XML 파싱하는 예제소스 입니다.



build.gradle 에 라이브러리 추가 (Gradle 사용 시)

// https://mvnrepository.com/artifact/com.thoughtworks.xstream/xstream

compile group: 'com.thoughtworks.xstream', name: 'xstream', version: '1.4.9' 


Gradle 사용하지 않고 진행 시 라이브러리는 직접 다운받아서 추가해 줍니다.



main 소스

package xmlparse;


import java.net.URL;

import java.net.URLConnection;


import com.thoughtworks.xstream.XStream;

import com.thoughtworks.xstream.io.xml.DomDriver;


import xmlparse.vo.Book;

import xmlparse.vo.Catalog;


public class xmlparse {


public static void main(String[] args) throws Exception {


// XStream 인스턴스 생성

        XStream xstream = new XStream(new DomDriver());

        

        // alias 설정 XML tag, 담당할 class 지정

        // 각 클래스는 해당 태그가 가진 항목을 구성하고 있다

        xstream.alias("catalog", Catalog.class);

        xstream.alias("book", Book.class);

        xstream.addImplicitCollection(Catalog.class, "books");

        

        // 태그의 어노테이션 처리 

        // <book id="xxx"> 에서 xxx 를 읽어오기 위해 필요하다

        // [REF] http://stackoverflow.com/questions/18106619/xstreamasattribute-not-adding-as-attribute-xstream

        //xstream.autodetectAnnotations(true);  // auto 속성을 지정하게 되면 모두 처리하는 듯 하다. (귀찮으면 걍 이거 쓰자 ;;)

        xstream.processAnnotations(Book.class); // 각 속성별로 읽어오도록 지정 한다.

        

        // XML 로드

        URL url = new URL("http://haebi.net/book.xml");

        URLConnection conn = url.openConnection();

        

        // 최상위 태그로부터 XML 파싱

        Catalog var = (Catalog)xstream.fromXML(conn.getInputStream());

        

        // 반복문 돌면서 처리한다

        for(int i=0; i<var.books.size(); i++)

        {

        Book book = var.books.get(i);

        System.out.println(book.id);

        System.out.println(book.author);

        }

        

}


book.java

package xmlparse.vo;


import com.thoughtworks.xstream.annotations.XStreamAlias;

import com.thoughtworks.xstream.annotations.XStreamAsAttribute;


@XStreamAlias("book")

public class Book {

@XStreamAsAttribute

    public String id;

public String author;

public String title;

public String genre;

public String price;

public String publish_date;

public String description;

// 갯수가 멀티개인 속성을 가지면...

//@XStreamImplicit(itemFieldName="reply")

//private ArrayList<string> reply

}


catalog.java

package xmlparse.vo;


import java.util.LinkedList;

import java.util.List;


import com.thoughtworks.xstream.annotations.XStreamAlias;

import com.thoughtworks.xstream.annotations.XStreamAsAttribute;


@XStreamAlias("catalog")

public class Catalog {

public List<Book> books = new LinkedList<Book>();

}



Depth 가 낮은 XML 처리에는 유용하겠는데, 깊어지면 답이 없어 보인다. ;;;

10 depth 까지 내려가면 클래스 언제 다 맹글어 -_-;;




Posted by 해비
2017. 4. 18. 01:54

XPath를 활용한 XML 파싱



syntaxhighliter 에서 코드가 뭉개져서 그냥 붙여넣기 했더니 보기가 영 그렇다.


gist 에 올린 소스가 더 이쁘게 보여지므로 참고

[gist 링크] https://gist.github.com/haebi/29070dda0556fc6fba5909b45a067faa



소스코드

package xmlparse2;


import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.xpath.XPath;

import javax.xml.xpath.XPathConstants;

import javax.xml.xpath.XPathFactory;


import org.w3c.dom.Document;

import org.w3c.dom.NodeList;


public class XmlParse2 {


public static void main(String[] args) throws Exception {

// 샘플 XML 파일(books.xml)

// [REF] https://msdn.microsoft.com/ko-kr/library/ms762271(v=vs.85).aspx

Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("http://haebi.net/book.xml");

// XPath 인스턴스 생성

XPath xpath = XPathFactory.newInstance().newXPath();

// 대상 노드 지정

String expression = "/catalog/book";

// 지정 노드로 부터 노드목록 획득

NodeList nl = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET);

// 첫번째 노드의 부모 노드명을 출력

System.out.println(nl.item(0).getParentNode().getNodeName());

System.out.println("sub node start!!");

System.out.println("-----------------------------------------------------");

// 1번째  book 노드의 자식노드 목록을 획득

NodeList cnl = nl.item(0).getChildNodes(); // author, title, genre, price, publish_date, description

System.out.println(cnl.item(0).getParentNode().getNodeName());


// 확보된 노드 목록을 순서대로 출력

for(int i=0; i<cnl.getLength(); i++)

{

// 노드 이름이 #text로 출력되는 문제로 스킵 하도록 설정하였다. 

// xml파일의 들여쓰기로 인한 문제 인듯 하다.

if("#text".equals(cnl.item(i).getNodeName()))

continue;

// 현재 노드 인덱스 번호 출력

System.out.println(i);

// 노드 명 출력

System.out.println("NODE : " + cnl.item(i).getNodeName());

// 노드 값 출력

System.out.println("VALUE : " + cnl.item(i).getTextContent());

}

System.out.println("-----------------------------------------------------");

}

}



출력

Start!!

catalog

sub node start!!

-----------------------------------------------------

book

1

NODE : author

VALUE : Gambardella, Matthew

3

NODE : title

VALUE : XML Developer's Guide

5

NODE : genre

VALUE : Computer

7

NODE : price

VALUE : 44.95

9

NODE : publish_date

VALUE : 2000-10-01

11

NODE : description

VALUE : An in-depth look at creating applications 

      with XML.

----------------------------------------------------- 




Posted by 해비