본문 바로가기

Dev.../웹서비스

[펌] XMLBeans 소개(2)

XMLBeans 소개 (2)
 
이번에는 지난 글에 이어 XMLBeans 가 가진 몇가지 기능들에 대해서 알아보도록 하겠다.
 
XML Curosr
 
XMLCursor 는 XML 을 Java Beans 유형으로 다루려할 때에 XML 문서상의 포인터를 JavaBeans 상에서 유지함으로써 보다 다루기 쉽도록 한 개념이다.
Cursor 의 입장에서보면 XML은 일련의 token이다.  그러한 token들은 token types 이라는 분류로 구분되어진다.  token types 는 START (for the beginning of an element), END (for its end), ATTR (for an attribute), and TEXT (for an element's text content) 등이 있다.
 

 




 
 
지난번에 살펴보았던 PO  문서를 다루는 예제를 다시한번 살펴보기로 한다.
에제에서 Line Item 을 추가하게 되면 item 은 항상 맨 마지막에 위치하게 된다.  그러나 만약 Item 의 itemDescription 으로 정렬된 형태로 Line Item 을 추가하려면 어떻게 해야 할까 ?
 
private static String addLineItemWithCursor(File purchaseOrder, String itemDescription,
    String perUnitOunces, String itemPrice, String itemQuantity)
{
    PurchaseOrderDocument poDoc = null;
    try
    {
        poDoc = PurchaseOrderDocument.Factory.parse(purchaseOrder);
    } catch (XmlException e)
    {
        e.printStackTrace();
    } catch (IOException e)
    {
        e.printStackTrace();
    }

    PurchaseOrderDocument.PurchaseOrder po = poDoc.getPurchaseOrder();

    // 정렬을 위하여 
    RuleBasedCollator collator =
        (RuleBasedCollator)Collator.getInstance(new Locale("en", "US", ""));
    XmlCursor cursor = po.newCursor();

    // Get the document's URI so you can use it to insert.
    String namespaceUri = cursor.namespaceForPrefix("");

    // Get the array of <line-item> elements.
    LineItem[] lineItems = po.getLineItemArray();

    // Loop through the element array to discover where to insert the new one.
    for (int i = 0; i < lineItems.length; i++)
    {
        LineItem lineItem = lineItems[i];

        // Find out if the new line item's description belongs before the
        // current line item's.
        int comparison = collator.compare(itemDescription, lineItem.getDescription());

        // 만약 비교결과가 -1 이라면 여기에 새로운 Item 을 추가하면 된다.
        if (comparison < 0)
        {
            cursor = lineItem.newCursor();

            // 새로운<line-item> element 를 생성한다.
            cursor.beginElement("line-item", namespaceUri);

            // 새로운 <description> element 를 생성하고 값을 채운다.                  
            cursor.beginElement("description", namespaceUri);
            cursor.insertChars(itemDescription);

            // 이하 엘리먼트들도 같은 방식으로 채운다.
            cursor.toNextToken();
            cursor.beginElement("per-unit-ounces", namespaceUri);
            cursor.insertChars(perUnitOunces);
            cursor.toNextToken();
            cursor.beginElement("prices", namespaceUri);
            cursor.insertChars(itemPrice);
            cursor.toNextToken();
            cursor.beginElement("quantity", namespaceUri);
            cursor.insertChars(itemQuantity);
               break;
        }
    }

    // Speed the cursor's garbage collection and return the updated XML.
    cursor.dispose();
    return poDoc.toString();
 
XQuery Expression 사용
 
XMLBeans 를 이용하면 특정 XML 를 잘라내거나 찾고자 할 경우 XQuery 를 이용할 수 있다.
다음의 예는 line-item 엘리먼트중 Price 가 20.00 보다 작거나 같은 line-item 만을 취하는 예제 이다.
 
PurchaseOrderDocument doc = PurchaseOrderDocument.Factory.parse(po); /* * The XQuery expression is the following two strings combined. They're * declared separately here for convenience. The first string declares * the namespace prefix that's used in the query expression; the second * declares the expression itself. */ String nsText = "declare namespace po = 'http://openuri.org/easypo'"; String pathText = "$this/po:purchase-order/po:line-item[po:price <= 20.00]"; String queryText = nsText + pathText; XmlCursor itemCursor = doc.newCursor().execQuery(queryText); System.out.println(itemCursor.xmlText());
위의 방식은 cursor 를 통하여 XQuery 를 실행시키는 예제이며 아래와 같이 사용할 수도 있다.
/* * Retrieve the matching phone elements and assign the results to the corresponding * generated type. */ LineItem[] items = (LineItem[])po.selectPath(queryText); /* * Loop through the results, printing the value 
 */ for (int i = 0; i < items.length; i++) { System.out.println(items[i].stringValue()); }

'Dev... > 웹서비스' 카테고리의 다른 글

[펌] WSDL  (0) 2005.02.13
[펌] Getting Started with XMLBean  (0) 2005.02.13
[펌] XMLBeans 소개(1)  (0) 2005.02.13
[온라인북] Programming Web Services with SOAP  (0) 2005.01.29
WebLogic의 기술적인 자료들이 풍부한 곳..  (0) 2005.01.29