blob: 404e8aecf47fcdb71718711718ebc568dabb0ae5 [file] [log] [blame]
<!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>Navigating XML with Cursors</title>
<!-- InstanceEndEditable -->
<!--(Meta)==========================================================-->
<meta http-equiv=Content-Type content="text/html; charset=$CHARSET;">
<!-- InstanceBeginEditable name="metatags" -->
<meta content="your name" name="author">
<meta content="A description of the topic contents." name="description">
<meta content="keywords to help in searches" name="keywords">
<meta content="10/25/02" name="date last modified">
<!-- 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> Navigating XML with Cursors </h1>
<div id="topictext">
<p>XML cursors are a way to navigate through an XML instance document. Once
you load an XML document, you can create a cursor to represent a specific
place in the XML. Because you can use a cursor with or without a schema corresponding
to the XML, cursors are an ideal way to handle XML without a schema.</p>
<p>With an XML cursor, you can:</p>
</div>
<UL>
<li>
<div><a href="conUnderstandingXMLTokens.html">Use the token model</a> to move
through XML in small increments, or in a manner similar to using a DOM-based
model.</div>
<LI>
<DIV>Get and set values within the XML.</DIV>
<LI>
<DIV><a href="#adding_elements_attributes">Change the structure</a> of an
XML document by inserting, removing, and moving elements and attributes.</DIV>
<LI>
<DIV><a href="conSelectingXMLwithXQueryPathXPath.html">Execute XQuery expressions</a>
against the XML represented by the cursor.</DIV>
<LI>
<DIV><a href="conUsingBookmarksToAnnotateXML.html">Insert bookmarks</a> to
mark locations in XML.</DIV>
</UL>
<P>When you're finished using a cursor, your code should call its <span class="langinline">dispose</span>
method.</P>
<h2>Creating and Moving a Cursor</h2>
<P>With an XML instance document bound to <span class="langinline"><a href="../reference/org/apache/xmlbeans/XmlObject.html">XmlObject</a></span>
(or a type inheriting from it), you create a new cursor by calling the <span class="langinline">newCursor</span>
method. The <span class="langinline"><a href="../reference/org/apache/xmlbeans/XmlCursor.html">XmlCursor</a></span>
interface represents a cursor. From a cursor standpoint, an XML document is
a collection of <EM>tokens</EM> that represent the kinds of things that can
appear in XML. These include&nbsp;attributes, the start and end of elements,
comments, and so on.&nbsp;Each piece of information in XML is represented by
a <em>token type</em>.</P>
<P class="notepara"><strong>Note:</strong> For a more complete description of
XML tokens, see <a href="conUnderstandingXMLTokens.html">Understanding XML Tokens</a>.</P>
<P>For example, the following code loads the&nbsp;XML instance described above
from a <span class="langinline">File</span> object, then creates a new cursor.
The <span class="langinline">toFirstChild</span> takes the cursor to the start
tag of the <span class="langinline">batchWidgetOrder</span> document element.
The code then prints the type for the token at the cursor's location, along
with the XML the cursor represents—in other words, <span class="filepath">Token
type: START /</span> and the <span class="filepath">batchWidgetOrderElement</span>
and its contents.</P>
<pre>public static void insertCursor(File orderFile) throws Exception
{
BatchWidgetOrderDocument xmlDoc = BatchWidgetOrderDocument.Factory.parse(orderFile);
XmlCursor orderCursor = xmlDoc.newCursor();
orderCursor.toFirstChild();
System.out.println("Token type: " + orderCursor.currentTokenType() +
" / " + orderCursor.xmlText());
}
</pre>
<p class="notepara"><STRONG>Note</STRONG>: The <span class="langinline">XmlCursor</span>
interface provides many methods you can use to put a cursor where you want it.
For a list of those methods, see <a href="../reference/org/apache/xmlbeans/XmlCursor.html">XmlCursor
Interface</a>.</p>
<h2><a name="adding_elements_attributes" id="adding_elements_attributes"></a>Adding
Elements and Attributes</h2>
<p>The <span class="langinline">XmlCursor</span> interface provides several methods
you can use to add elements and attributes to XML. </p>
<p>One way to add new XML is with the <span class="langinline">beginElement</span>
method. This method is designed to insert a new element at the cursor's location,
and do it so the cursor ends up between the new element's START and END tokens.
From this position, you can insert attributes (they're automatically placed
in the start tag, where they belong) and insert a value. Here's an example:</p>
<pre>
// Create a new chunk of XML.
XmlObject newXml = XmlObject.Factory.newInstance();
/*
* Insert a new cursor and move it to the first START token (where the
* XML actually begins.
*/
XmlCursor cursor = newXml.newCursor();
cursor.toNextToken();
// Begin a new item element whose namespace URI is "http://openuri.org".
cursor.beginElement(&quot;item&quot;, &quot;http://openuri.org/&quot;);
// Insert an ID attribute on the item element, along with an attribute value.
cursor.insertAttributeWithValue(&quot;id&quot;, &quot;4056404&quot;);
// Insert "bicycle" as an element value.
cursor.insertChars(&quot;bicycle&quot;);
cursor.dispose();
</pre>
<p>This example results in something like the following:</p>
<pre>&lt;ns1:item id=&quot;4056404&quot; xmlns:ns1=&quot;http://openuri.org/&quot;&gt;bicycle&lt;/ns1:item&gt;
</pre>
<h2> Using Stored Cursor Locations with push() and pop()</h2>
<div id="topictext">
<p>When you want to move a cursor around, but want to keep track of a former
location, you can use the <span class="langinline">XmlCursor</span> interface's
<span class="langinline">push</span> and <span class="langinline">pop</span>
methods. The <span class="langinline">push</span> method pushes the cursor's
current location onto a stack of locations maintained for that particular
cursor; the <span class="langinline">pop</span> method removes the location
from the top of the stack and moves the cursor to that location.</p>
<p>For example, consider the following &lt;employee&gt; element, used in the
example below.</p>
<pre>
&lt;employee&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&lt;name&gt;Gladys Kravitz&lt;/name&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&lt;address location=&quot;home&quot;&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;street&gt;1313 Mockingbird Lane&lt;/street&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;city&gt;Seattle&lt;/city&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;state&gt;WA&lt;/state&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;zip&gt;98115&lt;/zip&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&lt;/address&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&lt;address location=&quot;work&quot;&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;street&gt;2011 152nd Avenue NE&lt;/street&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;city&gt;Redmond&lt;/city&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;state&gt;WA&lt;/state&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;zip&gt;98052&lt;/zip&gt;
&nbsp;&nbsp; &nbsp;&lt;/address&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&lt;phone location=&quot;work&quot;&gt;(425) 555-6897&lt;/phone&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&lt;phone location=&quot;home&quot;&gt;(206) 555-6594&lt;/phone&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&lt;phone location=&quot;mobile&quot;&gt;(206) 555-7894&lt;/phone&gt;
&lt;/employee&gt;
</pre>
<p>The following Java code illustrates how you can use <span class="langinline">push</span>
and <span class="langinline">pop</span> to put the cursor back to a saved
location after a bit of traveling.</p>
<pre>
/**
* Pass to the trySelectPath method an XmlObject instance that contains
* the XML above.
*/
public void trySelectPath(XmlObject xml)
{
/*
* Inserts the cursor at the STARTDOC token (the very beginning,
* before any elements).
*/
XmlCursor cursor = xml.newCursor();
// Moves the cursor to just before &lt;employee&gt;
cursor.toFirstChild();
// Pushes the cursor's current location onto the stack.
cursor.push();
// Moves the cursor to just before the &quot;work&quot; &lt;phone&gt; element.
cursor.toChild(2);
// Moves the cursor to just before the &quot;home&quot; &lt;phone&gt; element.
cursor.toNextSibling();
// Moves the cursor back to just before &lt;employee&gt;
cursor.pop();
}
</pre>
<p>Of course, you can call <span class="langinline">push</span> and <span class="langinline">pop</span>
multiple times. Each new call to the <span class="langinline">push</span>
method pushes the current location onto the stack. As you call the <span class="langinline">pop</span>
method, you're always getting what's on top of the stack. So if you called
<span class="langinline">push</span> three times before calling <span class="langinline">pop</span>
&#8212; 1, 2, 3 &#8212; calling <span class="langinline">pop</span> three
times would get those locations in reverse order &#8212; 3, 2, 1.</p>
<p>The <span class="langinline">push</span> and <span class="langinline">pop</span>
methods can be handy as an alternative to creating new cursors that are designed
simply to mark a particular location while you move another cursor around.
The resources required to maintain a location stack through <span class="langinline">push</span>
and <span class="langinline">pop</span> are far less than those needed by
cursors. </p>
<H1>Disposing of a Cursor</H1>
<p>When you're through with a cursor, your code should call its <span class="langinline">dispose</span>
method to indicate that it's no longer needed.</p>
<p class="relatedtopics">Related Topics</p>
<p><a href="conUnderstandingXMLTokens.html">Understanding XML Tokens</a></p>
<p><a href="conGettingStartedwithXMLBeans.html">Getting Started with XMLBeans</a></p>
</div>
<!-- InstanceEndEditable -->
<script language="JavaScript">
</script>
</body>
</html>