IBM®
메인 컨텐츠로 가기
    Korea [국가변경]    이용약관
 
 
   
        제품    서비스 & 솔루션    고객지원 & 다운로드    회원 서비스    
메인 컨텐츠로 가기

한국 developerWorks  >  자바 | XML | 오픈 소스  >

JiBX 1.2, Part 2: XML 스키마를 Java 코드로 변환

XML 스키마에서 정돈된 형태의 사용자 정의 Java 코드 생성하기

developerWorks
Go to the previous page14 페이지 중 4 페이지Go to the next page

문서 옵션
PDF format - Fits A4 and Letter

PDF - Fits A4 and Letter
222 KB (36 pages)

Get Adobe® Reader®

샘플 코드


제안 및 의견
피드백

튜토리얼 평가

이 컨텐츠를 개선하기 위한 도움을 주십시오.


XML 문서 작업

이 섹션에서는 JiBX 바인딩 컴파일러를 실행하는 방법과 런타임에 JiBX를 사용하여 XML 문서 작업을 수행하는 방법에 대해 설명한다.

JiBX 바인딩 컴파일러 실행

생성된 바인딩 정의를 XML 문서 작업에 사용하려면 먼저 JiBX 바인딩 컴파일러를 실행해야 한다. 바인딩 컴파일러는 바인딩 정의에 지정된 대로 XML과의 상호 변환 기능을 실제로 구현한 바이트 코드를 컴파일된 클래스 파일에 추가한다. Java 클래스를 다시 컴파일하거나 바인딩 정의를 수정할 때마다 바인딩 컴파일러를 실행하여 바인딩 컴파일러 단계를 프로젝트의 표준 프로세스에 추가해야 한다.

바인딩 컴파일러는 JiBX 배포판의 jibx-bind.jar에 있다. JiBX 문서에서는 빌드 프로세스의 일부가 아닌 애플리케이션을 실행할 때 바인딩 컴파일러를 호출하는 방법을 비롯하여 여러 가지 실행 방법에 대해 자세히 설명한다. JiBX는 Eclipse 및 IntelliJ IDEA와 같은 IDE에서 작업할 때 바인딩 컴파일러를 자동으로 실행하는 Eclipse 및 IntelliJ IDEA용 플러그인도 제공한다.

이 튜토리얼에서는 편의상 Ant에서 바인딩 컴파일러를 실행한다. build.xml의 compile 대상은 생성된 코드와 제공된 테스트 프로그램을 모두 컴파일하여 바인딩을 준비하고 bind 대상은 바인딩 컴파일러를 실제로 실행한다. 그림 2에서는 이러한 대상을 실행할 때 표시되는 출력을 보여 준다. 여기에서는 codegen 대상을 이미 실행한 것으로 가정한다. (ant codegen compile bind와 같이 명령행에 차례대로 입력하여 세 대상을 차례대로 실행할 수도 있다.)


그림 2. Ant build compilebind 태스크
컴파일 및 바인딩 컴파일러에 대한 Ant build 출력



위로


런타임에 JiBX 사용

Listing 3에서는 생성된 스키마와 일치하는지 비교하는 간단한 테스트 문서를 보여 주며, 이 문서는 튜토리얼의 코드 다운로드에 starter.xml로 포함되어 있다.


Listing 3. order 스키마에 대한 테스트 문서

<order orderDate="2008-10-18" shipDate="2008-10-22" xmlns="http://jibx.org/starter">
  <orderNumber>12345678</orderNumber>
  <customer>
    <customerNumber>5678</customerNumber>
    <firstName>John</firstName>
    <lastName>Smith</lastName>
  </customer>
  <billTo state="WA" postCode="98059">
    <street1>12345 Happy Lane</street1>
    <city>Plunk</city>
    <country>USA</country>
  </billTo>
  <shipping>PRIORITY_MAIL</shipping>
  <shipTo state="WA" postCode="98034">
    <street1>333 River Avenue</street1>
    <city>Kirkland</city>
  </shipTo>
  <item quantity="1" price="5.99" id="FA9498349851"/>
  <item quantity="2" price="9.50" id="GC1234905049"/>
  <item quantity="1" price="8.95" id="AX9300048820"/>
</order>

다운로드 패키지에는 Listing 4와 같이 JiBX를 사용하여 문서를 마샬링언마샬링하는 방법을 보여 주는 간단한 테스트 프로그램도 있다. 마샬링은 원래 오브젝트에서 연결된 오브젝트를 포함하여 메모리에 있는 오브젝트에 대한 XML 표현을 생성하는 프로세스이며, 언마샬링은 XML 표현을 기반으로 메모리에 오브젝트(및 연결된 오브젝트 그래프)를 빌드하여 마샬링을 역으로 수행하는 프로세스이다. Ant run 대상은 Listing 3 문서를 입력으로 사용하여 이 테스트 프로그램을 실행하며 결과적으로 마샬링된 문서 사본이 out.xml 파일로 작성된다.


Listing 4. 테스트 프로그램
public class Test
{
    /**
     * Unmarshal the sample document from a file, compute and set order total, then
     * marshal it back out to another file.
     *
     * @param args
     */
    public static void main(String[] args) {
        if (args.length < 2) {
            System.out.println("Usage: java -cp ... " +
                "org.jibx.starter.Test in-file out-file");
            System.exit(0);
        }
        try {

            // unmarshal customer information from file
            IBindingFactory bfact = BindingDirectory.getFactory(Order.class);
            IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
            FileInputStream in = new FileInputStream(args[0]);
            Order order = (Order)uctx.unmarshalDocument(in, null);

            // compute the total amount of the order
            float total = 0.0f;
            for (Iterator<Item> iter = order.getItems().iterator(); iter.hasNext();) {
                Item item = iter.next();
                total += item.getPrice() * item.getQuantity();
            }
            order.setTotal(new Float(total));

            // marshal object back out to file (with nice indentation, as UTF-8)
            IMarshallingContext mctx = bfact.createMarshallingContext();
            mctx.setIndent(2);
            FileOutputStream out = new FileOutputStream(args[1]);
            mctx.setOutput(out, null);
            mctx.marshalDocument(order);
            System.out.println("Processed order with " +  order.getItems().size() +
                " items and total value " + total);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.exit(1);
        } catch (JiBXException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}

그림 3에서는 run 대상을 실행할 때 표시되는 출력을 보여 준다.


그림 3. Ant build run 태스크
테스트 프로그램을 실행한 Ant build 출력

이는 Part 1에서 사용한 테스트 프로그램과 동일한 프로그램으로 같은 제한 사항이 적용된다. Part 1에서와 같이 out.xml 파일에는 원래 문서를 언마샬링하여 가져온 order 데이터를 다시 마샬링하여 생성된 출력이 있다.




위로



Go to the previous page14 페이지 중 4 페이지Go to the next page
    IBM 소개 개인정보 보호정책 문의