File: conGettingStartedwithXMLBeans.html

package info (click to toggle)
xmlbeans 2.5.0-4
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 8,076 kB
  • sloc: java: 90,788; xml: 3,177; sh: 108; sql: 48; makefile: 29
file content (531 lines) | stat: -rw-r--r-- 29,001 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
<!doctype HTML public "-//W3C//DTD HTML 4.0 Frameset//EN">
<!-- Copyright 2004 The Apache Software Foundation

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License. -->
<html>
<head>
<!-- InstanceBeginEditable name="doctitle" -->
<title>Getting Started with XMLBeans</title>
<!-- InstanceEndEditable -->
<!--(Meta)==========================================================-->

<meta http-equiv=Content-Type content="text/html; charset=$CHARSET;">


<!-- InstanceBeginEditable name="metatags" -->

<meta name="author" content="your name">
<meta name="description" content="A description of the topic contents.">
<meta name="keywords" content="keywords to help in searches">
<meta name="date last modified" content="10/25/02">
<!-- InstanceEndEditable -->

<!--(Links)=========================================================-->
<!-- InstanceBeginEditable name="head" -->
<link href="../xmlbeans.css" rel="stylesheet" type="text/css">
<!-- InstanceEndEditable -->
<link href="../xmlbeans.css" rel="stylesheet" type="text/css">
<a href="../../../core/index.html" id="index"></a>
<script language="JavaScript" src="../../../core/topicInfo.js"></script>
<script language="JavaScript" src="../../../core/CookieClass.js"></script>
<script language="JavaScript" src="../../../core/displayContent.js"></script>
</head>

<!--(Body)==========================================================-->
<body>
<script language="JavaScript">

</script>
<!-- InstanceBeginEditable name="body" -->
<h1> Getting Started with XMLBeans</h1>
<div id="topictext">
  <p>XMLBeans provides intuitive ways to handle XML that make it easier for you
    to access and manipulate XML data and documents in Java. </p>
  <p>Characteristics of XMLBeans approach to XML:</p>
</div>
<ul>
  <li>
    <div>It provides a familiar Java object-based view of XML data without losing
      access to the original, native XML structure.</div>
  </li>
  <li>
    <div>The XML's integrity as a document is not lost with XMLBeans. XML-oriented
      APIs commonly take the XML apart in order to bind to its parts. With XMLBeans,
      the entire XML instance document is handled as a whole. The XML data is
      stored in memory as XML. This means that the document order is preserved
      as well as the original element content with whitespace.</div>
  </li>
  <li>
    <div>With types generated from schema, access to XML instances is through
      JavaBean-like accessors, with get and set methods.</div>
  </li>
  <li>
    <div>It is designed with XML schema in mind from the beginning &#8212; XMLBeans
      supports all XML schema definitions.</div>
  </li>
  <li>Access to XML is fast.</li>
</ul>
<div>
  <p>The starting point for XMLBeans is XML schema. A schema (contained in an
    XSD file) is an XML document that defines a set of rules to which other XML
    documents must conform. The XML Schema specification provides a rich data
    model that allows you to express sophisticated structure and constraints on
    your data. For example, an XML schema can enforce control over how data is
    ordered in a document, or constraints on particular values (for example, a
    birth date that must be later than 1900). Unfortunately, the ability to enforce
    rules like this is typically not available in Java without writing custom
    code. XMLBeans honors schema constraints.</p>
  <p class="notepara"><strong>Note:</strong> Where an XML schema defines rules
    for an XML document, an XML <em>instance</em> is an XML document that conforms
    to the schema.</p>
  <p>You compile a schema (XSD) file to generate a set of Java interfaces that
    mirror the schema. With these types, you process XML instance documents that
    conform to the schema. You bind an XML instance document to these types; changes
    made through the Java interface change the underlying XML representation.</p>
  <p>Previous options for handling XML include using XML programming interfaces
    (such as DOM or SAX) or an XML marshalling/binding tool (such as JAXB). Because
    it lacks strong schema-oriented typing, navigation in a DOM-oriented model
    is more tedious and requires an understanding of the complete object model.
    JAXB provides support for the XML schema specification, but handles only a
    subset of it; XMLBeans supports all of it. Also, by storing the data in memory
    as XML, XMLBeans is able to reduce the overhead of marshalling and demarshalling.</p>
  <h1>Accessing XML Using Its Schema</h1>
  <p>To get a glimpse of the kinds of things you can do with XMLBeans, take a
    look at an example using XML for a purchase order. The purchase order XML
    contains data exchanged by two parties, such as two companies. Both parties
    need to be able to rely on a consistent message shape, and a schema specifies
    the common ground. </p>
  <p>Here's what a purchase order XML instance might look like.</p>
  <pre>
&lt;po:purchase-order xmlns:po="http://openuri.org/easypo"&gt;
    &lt;po:customer&gt;
        &lt;po:name&gt;Gladys Kravitz&lt;/po:name&gt;
        &lt;po:address&gt;Anytown, PA&lt;/po:address&gt;
    &lt;/po:customer&gt;
    &lt;po:date&gt;2003-01-07T14:16:00-05:00&lt;/po:date&gt;
    &lt;po:line-item&gt;
        &lt;po:description&gt;Burnham's Celestial Handbook, Vol 1&lt;/po:description&gt;
        &lt;po:per-unit-ounces&gt;5&lt;/po:per-unit-ounces&gt;
        &lt;po:price&gt;21.79&lt;/po:price&gt;
        &lt;po:quantity&gt;2&lt;/po:quantity&gt;
    &lt;/po:line-item&gt;
    &lt;po:line-item&gt;
        &lt;po:description&gt;Burnham's Celestial Handbook, Vol 2&lt;/po:description&gt;
        &lt;po:per-unit-ounces&gt;5&lt;/po:per-unit-ounces&gt;
        &lt;po:price&gt;19.89&lt;/po:price&gt;
        &lt;po:quantity&gt;2&lt;/po:quantity&gt;
    &lt;/po:line-item&gt;
&lt;po:shipper&gt;
        &lt;po:name&gt;ZipShip&lt;/po:name&gt;
        &lt;po:per-ounce-rate&gt;0.74&lt;/po:per-ounce-rate&gt;
    &lt;/po:shipper&gt;
&lt;/po:purchase-order&gt;</pre>
  <p>This XML includes a root element, <span class="langinline">purchase-order</span>,
    that has three kinds of child elements: <span class="langinline">customer</span>,
    <span class="langinline">date</span>, <span class="langinline">line-item</span>,
    and <span class="langinline">shipper</span>. An intuitive, object-based view
    of this XML would provide an object representing the <span class="langinline">purchase-order</span>
    element, and it would have methods for getting the date and for getting subordinate
    objects for <span class="langinline">customer</span>, <span class="langinline">line-item</span>,
    and <span class="langinline">shipper</span> elements. Each of the last three
    would have its own methods for getting the data inside them as well.</p>
  <h2>Looking at the Schema</h2>
  <p>The following XML is the the schema for the preceding purchase order XML.
    It defines the XML's &quot;shape&quot; &#8212; what its elements are, what
    order they appear in, which are children of which, and so on.</p>
</div>
<div>
  <pre>
&lt;xs:schema targetNamespace="http://openuri.org/easypo"
    xmlns:po="http://openuri.org/easypo"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    elementFormDefault="qualified"&gt;

    &lt;xs:element name="purchase-order"&gt;
        &lt;xs:complexType&gt;
            &lt;xs:sequence&gt;
                &lt;xs:element name="customer" type="po:customer"/&gt;
                &lt;xs:element name="date" type="xs:dateTime"/&gt;
                &lt;xs:element name="line-item" type="po:line-item" minOccurs="0" maxOccurs="unbounded"/&gt;
                &lt;xs:element name="shipper" type="po:shipper" minOccurs="0"/&gt;
            &lt;/xs:sequence&gt;
        &lt;/xs:complexType&gt;
    &lt;/xs:element&gt;
    &lt;xs:complexType name="customer"&gt;
        &lt;xs:sequence&gt;
            &lt;xs:element name="name" type="xs:string"/&gt;
            &lt;xs:element name="address" type="xs:string"/&gt;
        &lt;/xs:sequence&gt;
    &lt;/xs:complexType&gt;
    &lt;xs:complexType name="line-item"&gt;
        &lt;xs:sequence&gt;
            &lt;xs:element name="description" type="xs:string"/&gt;
            &lt;xs:element name="per-unit-ounces" type="xs:decimal"/&gt;
            &lt;xs:element name="price" type="xs:double"/&gt;
            &lt;xs:element name="quantity" type="xs:int"/&gt;
        &lt;/xs:sequence&gt;
    &lt;/xs:complexType&gt;
    &lt;xs:complexType name="shipper"&gt;
        &lt;xs:sequence&gt;
            &lt;xs:element name="name" type="xs:string"/&gt;
            &lt;xs:element name="per-ounce-rate" type="xs:decimal"/&gt;
        &lt;/xs:sequence&gt;
    &lt;/xs:complexType&gt;
&lt;/xs:schema&gt;</pre>
  <div>
    <p>This schema describes the purchase order XML instance by defining the following:</p>
  </div>
  <ul>
    <li>
      <div>Definitions for three complex types &#8212; customer, line-item, and
        shipper. These are the types used for the children of the purchase-order
        element. In schema, a complex type is one that defines an element that
        may have child elements and attributes. The sequence element nested in
        the complex type lists its child elements.</div>
      <p>These are also <em>global</em> types. They are global because they are
        at the top level of the schema (in other words, just beneath the <span class="langinline">schema</span>
        root element). This means that they may be referenced from anywhere else
        in the schema.</p>
    </li>
  </ul>
</div>
<div>
  <ul>
    <li>Use of simple types within the complex types. The name, address, and description
      elements (among others) are typed as simple types. As it happens, these
      are also <em>built-in</em> types. A built-in type (here, one with the &quot;xs&quot;
      prefix) is part of the schema specification. (The specification defines
      46 built-in types.)</li>
    <li>A global element called purchase-order. This element definition includes
      a nested complex type definition that specifies the child elements for a
      purchase-order element. Notice that the complex type includes references
      to the other complex types defined in this schema.</li>
  </ul>
  <div></div>
  <p>In other words, the schema defines types for the child elements and describes
    their position as subordinate to the root element, <span class="langinline">purchase-order</span>.</p>
  <p>When you use the XMLBean compiler with an XSD file such as this one, you
    generate a JAR file containing the interfaces generated from the schema.</p>
  <h2>Writing Java Code That Uses the Interfaces</h2>
  <p>With the XMLBeans interfaces in your application, you can write code that
    uses the new types to handle XML based on the schema. Here's an example that
    extracts information about each of the ordered items in the purchase order
    XML, counts the items, and calculates a total of their prices. In particular,
    look at the use of types generated from the schema and imported as part of
    the <span class="langinline">org.openuri.easypo</span> package. </p>
  <p>The <span class="langinline">printItems</span> method receives a <span class="langinline">File</span>
    object containing the purchase order XML file.</p>
  <pre>
package docs.xmlbeans;

import java.io.File;
import org.apache.xmlbeans.*;
import org.openuri.easypo.PurchaseOrderDocument;
import org.openuri.easypo.PurchaseOrder;
import org.openuri.easypo.LineItem;

public class POHandler
{
    public static void printItems(File po) throws Exception
    {
        /*
         * All XMLBeans schema types provide a nested Factory class you can
         * use to bind XML to the type, or to create new instances of the type.
         * Note that a "Document" type such as this one is an XMLBeans
         * construct for representing a global element. It provides a way
         * for you to get and set the contents of the entire element.
         *
         * Also, note that the parse method will only succeed if the
         * XML you're parsing appears to conform to the schema.
         */
        PurchaseOrderDocument poDoc =
            PurchaseOrderDocument.Factory.parse(po);

        /*
         * The PurchaseOrder type represents the purchase-order element's
         * complex type.
         */
        PurchaseOrder po = poDoc.getPurchaseOrder();

        /*
         * When an element may occur more than once as a child element,
         * the schema compiler will generate methods that refer to an
         * array of that element. The line-item element is defined with
         * a maxOccurs attribute value of "unbounded", meaning that
         * it may occur as many times in an instance document as needed.
         * So there are methods such as getLineItemArray and setLineItemArray.
         */
        LineItem[] lineitems = po.getLineItemArray();
        System.out.println("Purchase order has " + lineitems.length + " line items.");

        double totalAmount = 0.0;
        int numberOfItems = 0;

        /*
         * Loop through the line-item elements, using generated accessors to
         * get values for child elements such a description, quantity, and
         * price.
         */
        for (int j = 0; j < lineitems.length; j++)
        {
            System.out.println(" Line item: " + j);
            System.out.println(
                "   Description: " + lineitems[j].getDescription());
            System.out.println("   Quantity: " + lineitems[j].getQuantity());
            System.out.println("   Price: " + lineitems[j].getPrice());
            numberOfItems += lineitems[j].getQuantity();
            totalAmount += lineitems[j].getPrice() * lineitems[j].getQuantity();
        }
        System.out.println("Total items: " + numberOfItems);
        System.out.println("Total amount: " + totalAmount);
    }
}
</pre>
  <p>Notice that types generated from the schema reflect what's in the XML:</p>
</div>
<ul>
  <li>
    <div>A <span class="langinline">PurchaseOrderDocument</span> represents the
      global root element.</div>
  </li>
  <li>
    <div>A <span class="langinline">getPurchaseOrder</span> method returns a <span class="langinline">PurchaseOrderDocument.PurchaseOrder</span>
      type that contains child elements, including <span class="langinline">line-item</span>.
      A <span class="langinline">getLineItemArray</span> method returns a <span class="langinline">LineItem</span>
      array containing the <span class="langinline">line-item</span> elements.</div>
  </li>
  <li>Other methods, such as <span class="langinline">getQuantity</span>, <span class="langinline">getPrice</span>,
    and so on, follow naturally from what the schema describes, returning corresponding
    children of the <span class="langinline">line-item</span> element.</li>
  <li>The name of the package containing these types is derived from the schema's
    target namespace.</li>
</ul>
<div>
  <p>Capitalization and punctuation for generated type names follow Java convention.
    Also, while this example parses the XML from a file, other <span class="langinline">parse</span>
    methods support a Java <span class="langinline">InputStream</span> object,
    a <span class="langinline">Reader</span> object, and so on.</p>
  <p>The preceding Java code prints the following to the console:</p>
</div>
<div>
  <pre>
Purchase order has 3 line items.
 Line item 0
   Description: Burnham's Celestial Handbook, Vol 1
   Quantity: 2
   Price: 21.79
 Line item 1
   Description: Burnham's Celestial Handbook, Vol 2
   Quantity: 2
   Price: 19.89
Total items: 4
Total amount: 41.68</pre>
  <h2>Creating New XML Instances from Schema</h2>
  <p>As you've seen XMLBeans provides a &quot;factory&quot; class you can use
    to create new instances. The following example creates a new <span class="langinline">purchase-order</span>
    element and adds a <span class="langinline">customer</span> child element.
    It then inserts <span class="langinline">name</span> and <span class="langinline">address</span>
    child elements, creating the elements and setting their values with a single
    call to their <span class="langinline">set</span> methods.</p>
  <pre>
public PurchaseOrderDocument createPO()
{
&nbsp;&nbsp;&nbsp;&nbsp;PurchaseOrderDocument newPODoc = PurchaseOrderDocument.Factory.newInstance();
&nbsp;&nbsp;&nbsp;&nbsp;PurchaseOrder newPO = newPODoc.addNewPurchaseOrder();
&nbsp;&nbsp;&nbsp;&nbsp;Customer newCustomer = newPO.addNewCustomer();
&nbsp;&nbsp;&nbsp;&nbsp;newCustomer.setName(&quot;Doris Kravitz&quot;);
&nbsp;&nbsp;&nbsp;&nbsp;newCustomer.setAddress(&quot;Bellflower, CA&quot;);
&nbsp;&nbsp;&nbsp;&nbsp;return newPODoc;
}
</pre>
  <p>The following is the XML that results. Note that XMLBeans assigns the correct
    namespace based on the schema, using an &quot;ns1&quot; (or, &quot;namespace
    1&quot;) prefix. For practical purposes, the prefix itself doesn't really
    matter &#8212; it's the namespace URI (http://openuri.org/easypo) that defines
    the namespace. The prefix is merely a marker that represents it.</p>
  <pre>&lt;ns1:purchase-order xmlns:ns1=&quot;http://openuri.org/easypo&quot;&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&lt;ns1:customer&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;ns1:name&gt;Doris Kravitz&lt;/ns1:name&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;ns1:address&gt;Bellflower, CA&lt;/ns1:address&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&lt;/ns1:customer&gt;
&lt;/ns1:purchase-order&gt;
</pre>
  <p>Note that all types (including those generated from schema) inherit from
    <span class="langinline">XmlObject</span>, and so provide a <span class="langinline">Factory</span>
    class. For an overview of the type system in which <span class="langinline">XmlObject</span>
    fits, see <a href="conXMLBeansSupportBuiltInSchemaTypes.html">XMLBeans Support
    for Built-In Schema Types</a>. For reference information, see <a href="../reference/org/apache/xmlbeans/XmlObject.html">XmlObject
    Interface</a>.</p>
  <h1>XMLBeans Hierarchy</h1>
  <p>The generated types you saw used in the preceding example are actually part
    of a hierarchy of XMLBeans types. This hierarchy is one of the ways in which
    XMLBeans presents an intuitive view of schema. At the top of the hierarchy
    is <span class="langinline">XmlObject</span>, the base interface for XMLBeans
    types. Beneath this level, there are two main type categories: generated types
    that represent user-derived schema types, and included types that represent
    built-in schema types.</p>
  This topic has already introduced generated types. For more information, see
  <a href="conJavaTypesGeneratedFromUserDerived.html">Java Types Generated from
  User-Derived Schema Types.</a>
  <h2>Built-In Type Support</h2>
  <p>In addition to types generated from a given schema, XMLBeans provides 46
    Java types that mirror the 46 built-in types defined by the XML schema specification.
    Where schema defines <span class="langinline">xs:string</span>, <span class="langinline">xs:decimal</span>,
    and <span class="langinline">xs:int</span>, for example, XMLBeans provides
    <span class="langinline"><a href="../reference/org/apache/xmlbeans/XmlString.html">XmlString</a></span>,
    <span class="langinline"><a href="../reference/org/apache/xmlbeans/XmlDecimal.html">XmlDecimal</a></span>,
    and <span class="langinline"><a href="../reference/org/apache/xmlbeans/XmlInt.html">XmlInt</a></span>.
    Each of these also inherits from <span class="langinline">XmlObject</span>,
    which corresponds to the built-in schema type <span class="langinline">xs:anyType</span>.</p>
  <p>XMLBeans provides a way for you to handle XML data as these built-in types.
    Where your schema includes an element whose type is, for example, <span class="langinline">xs:int</span>,
    XMLBeans will provide a generated method designed to return an <span class="langinline">XmlInt</span>.
    In addition, as you saw in the preceding example, for most types there will
    also be a method that returns a natural Java type such as <span class="langinline">int</span>.
    The following two lines of code return the <span class="langinline">quantity</span>
    element's value, but return it as different types.</p>
  <pre>
// Methods that return simple types begin with an "x".
XmlInt xmlQuantity = lineitems[j].xgetQuantity();
// Methods that return a natural Java type are unadorned.
int javaQuantity = lineitems[j].getQuantity();
</pre>
  <p>In a sense both get methods navigate to the <span class="langinline">quantity</span>
    element; the <span class="langinline">getQuantity</span> method goes a step
    further and converts the elements value to the most appropriate natural Java
    type before returning it. (XMLBeans also provides a means for validating the
    XML as you work with it.)</p>
  <p>If you know a bit about XML schema, XMLBeans types should seem fairly intuitive.
    If you don't, you'll learn a lot by experimenting with XMLBeans using your
    own schemas and XML instances based on them. </p>
  <p>For more information on the methods of types generated from schema, see <a href="conMethodsForGeneratedJavaTypes.html">Methods
    for Types Generated From Schema</a>. For more about the how XMLBeans represents
    built-in schema types, see <a href="conXMLBeansSupportBuiltInSchemaTypes.html">XMLBeans
    Support for Built-In Schema Types</a>.</p>
  <h1>Using XQuery Expressions</h1>
  <p>With XMLBeans you can use XQuery to query XML for specific pieces of data.
    XQuery is sometimes referred to as &quot;SQL for XML&quot; because it provides
    a mechanism to access data directly from XML documents, much as SQL provides
    a mechanism for accessing data in traditional databases.</p>
  <p>XQuery borrows some of its syntax from XPath, a syntax for specifying nested
    data in XML. The following example returns all of the <span class="langinline">line-item</span>
    elements whose <span class="langinline">price</span> child elements have values
    less than or equal to 20.00:</p>
  <pre>
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());
</pre>
  <p>This code creates a new cursor at the start of the document. From there,
    it uses the <span class="langinline">XmlCursor</span> interface's <span class="langinline">execQuery</span>
    method to execute the query expression. In this example, the method's parameter
    is an XQuery expression that simply says, &quot;From my current location,
    navigate through the <span class="langinline">purchase-order</span> element
    and retrieve those <span class="langinline">line-item</span> elements whose
    value is less than or equal to 20.00.&quot; The <span class="langinline">$this</span>
    variable means &quot;the current position.&quot;</p>
  <p>For more information about XQuery, see <a href="http://www.w3.org/TR/xquery/" target="_blank">XQuery
    1.0: An XML Query Language</a> at the W3C web site.</p>
  <h2>Using XML Cursors</h2>
  <p>In the preceding example you may have noticed the <span class="langinline"><a href="../reference/org/apache/xmlbeans/XmlCursor.html">XmlCursor</a></span>
    interface. In addition to providing a way to execute XQuery expression, an
    XML cursors offers a fine-grained model for manipulating data. The XML cursor
    API, analogous to the DOM's object API, is simply a way to point at a particular
    piece of data. So, just like a cursor helps navigate through a word processing
    document, the XML cursor defines a location in XML where you can perform actions
    on the selected XML.</p>
  <p>Cursors are ideal for moving through an XML document when there's no schema
    available. Once you've got the cursor at the location you're interested in,
    you can perform a variety of operations with it. For example, you can set
    and get values, insert and remove fragments of XML, copy fragments of XML
    to other parts of the document, and make other fine-grained changes to the
    XML document.</p>
  <p>The following example uses an XML cursor to navigate to the <span class="langinline">customer</span>
    element's <span class="langinline">name</span> child element.</p>
  <pre>
PurchaseOrderDocument doc =
    PurchaseOrderDocument.Factory.parse(po);

XmlCursor cursor = doc.newCursor();
cursor.toFirstContentToken();
cursor.toFirstChildElement();
cursor.toFirstChildElement();
System.out.println(cursor.getText());

cursor.dispose();
</pre>
  <p>What's happening here? As with the earlier example, the code loads the XML
    from a <span class="langinline">File</span> object. After loading the document,
    the code creates a cursor at its beginning. Moving the cursor a few times
    takes it to the nested <span class="langinline">name </span> element. Once
    there, the getText method retrieves the element's value.</p>
  <p>This is just an introduction to XML cursors. For more information about using
    cursors, see <a href="conNavigatingXMLwithCursors.html">Navigating XML with
    Cursors</a>.</p>
  <h2>Where to Go Next</h2>
</div>
<ul>
  <li>
    <div>XMLBeans provides intuitive ways to handle XML, particularly if you're
      starting with schema. If you're accessing XML that's based on a schema,
      you'll probably find it most efficient to access the XML through generated
      types specific to the schema. To do this, you begin by compiling the schema
      to generate interfaces. For more information on using XMLBeans types generated
      by compiling schema, see <a href="conJavaTypesGeneratedFromUserDerived.html">Java
      Types Generated From User-Derived Schema Types</a> and <a href="conMethodsForGeneratedJavaTypes.html">Methods
      for Types Generated From Schema</a>.</div>
  </li>
  <li>
    <div>You might be interested in reading more about the type system on which
      XMLBeans is based, particularly if you're using types generated from schema.
      XMLBeans provides a hierarchical system of types that mirror what you find
      in the XML schema specification itself. If you're working with schema, you
      might find it helps to understand how these types work. For more information,
      see <a href="conXMLBeansSupportBuiltInSchemaTypes.html">XMLBeans Support
      for Built-In Schema Types</a> and <a href="conIntroToTheSchemaTypeSystem.html">Introduction
      to Schema Type Signatures</a>.</div>
  </li>
  <li>
    <div>XMLBeans provides access to XML through XQuery, which borrows path syntax
      from XPath. With XQuery, you can specify specific fragments of XML data
      with or without schema. To learn more about using XQuery and XPath in XMLBeans,
      see <a href="conSelectingXMLwithXQueryPathXPath.html">Selecting XML with
      XQuery and XPath</a>.</div>
  </li>
  <li>You can use the <span class="langinline">XmlCursor</span> interface for
    fine-grained navigation and manipulation of XML. For more information, see
    <a href="conNavigatingXMLwithCursors.html">Navigating XML with Cursors</a>.</li>
</ul>
<div>
  <p class="notepara"><strong>Note:</strong> The xbean.jar file that contains
    the XMLBeans library is fully functional as a standalone library.</p>
  <h1>Related Topics</h1>
  <p><a href="../../samples/navXMLBeansSamples.html">XMLBeans Samples</a></p>
</div>
<!-- InstanceEndEditable -->
<script language="JavaScript">

</script>
</body>
</html>