Google AdSense


[Java] Castor를 이용한 XML 데이터 바인딩 by Sigel

XML 파일의 내용을 자바 객체로 바인딩을 해주는 Castor라는 간편한 프레임웍이 있다. 오늘 또 신나게 가지고 놀았다. 사실 XML 파일의 스키마만 있으면 Castor에서 제공하는 Code Generator를 이용해서 정말 간편하게 만들 수 있지만, 스키마가 없다. -ㅅ-;; 그래서 조금 시간이 걸렸다.

<?xml version="1.0" encoding="UTF-8"?>
<bookshelf>
    <book>
        <title>공부가 제일 어려웠어요 -ㅅ-</title>
        <author>나</author>
        <price currency="won">500000</price>
    </book>
    <book>
        <title>Harry Potter</title>
        <author>J.K. Rowling</author>
        <price currency="dollar">20</price>
    </book>
</bookshelf>
testData.xml - 이 녀석을 읽을 것이다.

File mappingFile = new File("src/test/castor/dataMapping.xml");
File dataFile = new File("src/test/castor/testData.xml");
InputSource is = new InputSource(new FileInputStream(dataFile));
Mapping mapping = new Mapping();
mapping.loadMapping(new InputSource(new FileInputStream(mappingFile)));
Unmarshaller unmarshaller = new Unmarshaller(Bookshelf.class);
unmarshaller.setMapping(mapping);
Bookshelf data = (Bookshelf) unmarshaller.unmarshal(is);

// 읽어온 것 보여주고..
List <Book> books = data.getBooks();
for(Book item : books)
{
    System.out.println(item.getTitle());
    System.out.println(item.getAuthor());
    System.out.println(item.getPrice() + " (" + item.getPriceCurrency() + ")");
    System.out.println();
}

// 다른 파일에 써보자..
// Castor의 아쉬운 점은 줄바꿈이 되지 않는다 TㅅT
File newDataFile = new File("src/test/castor/newTestData.xml");
FileWriter fw = new FileWriter(newDataFile);
Marshaller marshaller = new Marshaller(fw);
marshaller.setEncoding("euc-kr");
marshaller.marshal(books);
CastorTest.java - XML 파일을 읽어 Bookshelf와 Book 클래스 객체 생성 (바인딩)

public class Bookshelf
{
    private List <Book> books = new ArrayList <Book> ();

    public List <Book> getBooks()
    {
        return this.books;
    }
}
Bookshelf.Java

public class Book
{
    private String title;
    private String author;
    private int price;
    private String priceCurrency;

    public String getTitle()
    {
        return title;
    }

    public void setTitle(String title)
    {
    this.title = title;
    }

    public String getAuthor()
    {
    return author;
    }

    public void setAuthor(String author)
    {
    this.author = author;
    }

    public int getPrice()
    {
        return price;
    }

    public void setPrice(int price)
    {
        this.price = price;
    }

    public String getPriceCurrency()
    {
        return priceCurrency;
    }

    public void setPriceCurrency(String priceCurrency)
    {
        this.priceCurrency = priceCurrency;
    }
}
Book.java


<?xml version="1.0"?>
<mapping>
    <class name="test.castor.Bookshelf">
        <map-to xml="bookshelf" />

        <field name="books" type="test.castor.Book" collection="arraylist">
            <!-- arraylist이외에 여러 종류의 Collection으로 받을 수 있다. -->
            <bind-xml name="book" />
    </field>
    </class>

    <class name="test.castor.Book">
    <field name="title" type="string">
            <bind-xml name="title" node="element" />
        </field>
        <field name="author" type="string">
            <bind-xml name="author" node="element" />
        </field>
        <field name="price" type="integer">
            <bind-xml name="price" node="element" />
        </field>
        <field name="priceCurrency" type="string">
            <bind-xml name="currency" node="attribute" location="price" />
        </field>
    </class>
</mapping>
dataMapping.xml - 그리고 중요한 매핑 파일

Book 클래스와 Bookshelf 클래스의 필드에 어떤 element, attribute를 넣어야 하는지 정의된 매핑 파일이다. 가장 시간을 많이 뺏긴 녀석 -ㅅ-;;


예제 이외의 더 자세한 내용은 아래 사이트 참고

The Castor Project
[JAVA] Castor XML Parser 데이터 바인딩
Data binding with Castor, Part 3: Map between schemas
Castor - XML Data Binding
Castor XML Mapping

트랙백

이 글과 관련된 글 쓰기 (트랙백 보내기)
TrackbackURL : http://entireboy.egloos.com/tb/3863564 [도움말]

덧글

덧글 입력 영역