poi/xmlbeans/docs/guide/conValidationWithXmlBeans.html
2018-02-16 22:41:27 +00:00

1 line
13 KiB
HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- 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 xmlns="http://www.w3.org/1999/xhtml">
<head>
<!-- InstanceBeginEditable name="doctitle" -->
<title>XMLBeans Tools</title>
<!-- InstanceEndEditable -->
<!--(Meta)==========================================================-->
<meta http-equiv=Content-Type content="text/html; charset=iso-8859-1">
<!-- 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">
<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> Validation with XMLBeans </h1>
<p>An essential part of schema-related work is validating instances based on the schema. XMLBeans provides a number of ways for you to ensure your instances are valid, both at the command line and programmatically at run time. </p>
<h2>Validation, XMLBeans-Style</h2>
<p>XMLBeans' schema-oriented approach to handling XML makes validation an important part of its work. However, XMLBeans has a specific approach to validation that's helpful to keep in mind when you're working.</p>
<p>Validation features include the following: </p>
<ul>
<li>Generally, XMLBeans validates when you ask it to. It <a href="#no_parsing_validation">doesn't validate while parsing</a> -- nor, by default, while your code is updating the bound instance along the way through, say, set* methods (although you can change this behavior).</li>
<li>You can <a href="#validation_apis">validate programmatically</a> or by using one of the <a href="#command_line_validation">command-line tools</a> provided by XMLBeans. </li>
<li>The <code>validate</code> methods return <code>true</code> or <code>false</code> to indicate whether the instance is valid. You can also <a href="#retrieving_error_messages">capture error information</a> if you want to when validating programmatically. To do this, you specify an error listener.</li>
<li>You can tell XMLBeans at parse time that it <a href="#validation_as_you_go">should validate during calls to set* methods</a>. Note that this means validation <em>after</em> parsing, not during, and that it can slow performance. Also note validation would not occur as changes are made by a cursor.</li>
<li>XMLBeans does validate <em>schema</em> when compiling the schema through scomp or the xmlbean Ant task. (When you're compiling schema programmatically, you can disable validation with the <code>XmlOptions.setCompileNoValidation</code> method.)</li>
</ul>
<h2>XMLBeans Validates Only When You Ask It To &#8212; Generally</h2>
<p>Given XMLBeans' focus on schema-oriented work, it's natural to assume that it might check up on you as your code is making changes to an instance &#8212; that it might prevent your code from doing something that would render the instance invalid along the way. But, by default, it doesn't. The design of XMLBeans assumes that an XML instance might go through multiple invalid states before changes are complete. As a result, generally speaking, XMLBeans keeps quiet while changes are occurring.</p>
<blockquote>
<p><span class="notepara"><strong>Note:</strong> The exception to this rule is that XMLBeans validates your schema when you're compiling it using scomp or the xmlbean Ant task.</span></p>
</blockquote>
<h3><a name="no_parsing_validation" id="no_parsing_validation"></a>XMLBeans Does Not Validate an Instance While Parsing It</h3>
<p>But it's not hard to get the impression that it does. For example, imagine that you're parsing an XML instance using a statement such as the following:</p>
<blockquote>
<pre>MyXmlSchemaType myXmlBean = MyXmlSchemaType.Factory.parse(myXml);</pre>
</blockquote>
<p>If the namespace declared in the myXml instance doesn't match the target namespace of the schema from which MyXmlSchemaType was generated, parsing will fail with an error message. Likewise, you'll get messages for other mismatches between the shape of myXml and the XML shape described by the schema.</p>
<p>But these failures and messages don't result from validation. Instead, all XMLBeans is doing is a not-very-deep check to see if the instance <em>shouldn't be bound</em> to the XMLBeans type generated from schema. In other words, the checking done at the parsing stage is simply a &quot;low bar&quot; effort to avoid trouble down the road.</p>
<p>Validation, on the other hand, is designed to verify that the instance conforms completely to the schema.</p>
<p>So you can validate in any of three ways:</p>
<ul>
<li>On request, using a validate method.</li>
<li>On the fly, using the &quot;validate on set&quot; option.</li>
<li>Using one of the command-line tools. </li>
</ul>
<h2>Tools for Validating</h2>
<p>XMLBeans tools for validation include command-line tools and APIs. </p>
<h3><a name="command_line_validation" id="command_line_validation"></a>Command-line Tools for Validation </h3>
<p>Among the many <a href="tools.html">command-line tools</a> XMLBeans provides, you'll find two that are specifically for validation. </p>
<ul>
<li><a href="tools.html#validate">validate</a> tool &#8212; A validation command-line tool
in which you specify the instance to validate and the schema to validate it against.
<p>You'll find the <code>validate</code> tool in the bin directory of your XMLBeans installation. </p>
</li>
<li><a href="tools.html#svalidate">svalidate</a> tool &#8212; Identical to the validate tool, except that svalidate uses a streaming model that supports validation against much larger schemas.
<p>You'll find the <code>svalidate</code> tool in the bin directory of your XMLBeans installation. </p>
</li>
</ul>
<h3><a name="validation_apis" id="validation_apis"></a>APIs for Validation </h3>
<p>XMLBeans APIs provide ways for you to <a href="#validation_when_you_ask">validate on request</a> &#8212; say, after your code has finished editing an instance and before it passes the instance elsewhere. You can also specify that your calls to set* methods should <a href="#validation_as_you_go">validate on-the-fly</a> the instance that is being edited; you do this as an option when your code creates the XMLBeans schema type instance.</p>
<h4><a name="validation_when_you_ask" id="validation_when_you_ask"></a>Validation When You Ask for It</h4>
<p>Both the <code>validate</code> methods described here are available from any XMLBeans type generated from schema during schema compilation (because all such types inherit from <code>XmlObject</code>). Both methods are designed to validate the instance that is bound to the type from which the method is called. For example, if your schema defines a <code>&lt;purchase-order&gt;</code> element with <code>&lt;item&gt;</code> children, calling the <code>myItem.validate()</code> method will validate the <code>&lt;item&gt;</code> instance bound to <code>Item</code>. This includes the <code>&lt;item&gt;</code> element's children, but not the <code>&lt;purchase-order&gt;</code> element or the <code>&lt;item&gt;</code> element's siblings.</p>
<p>Both methods return a <code>boolean</code> to indicate validity, and one of the methods lets you specify options for validation, such as capturing messages about why an invalid instance is invalid.</p>
<ul>
<li><code>XmlObject.validate()</code> &#8212; Returns <code>true</code> if the instance is valid.</li>
<li><code>XmlObject.validate(XmlOptions)</code> &#8212; Returns <code>true</code> if the instance is valid, using the specified <code>XmlOptions</code> instance to customize validation.
<p>In particular, you can use the <code>XmlOptions.setErrorListener</code> method to specify a <code>Collection</code> instance with which to capture messages pertaining to invalid instances. For an example, see the Javadoc for this method. </p>
<p>Through the <code>XmlOptions</code> class, you can specify options to use during validation. The options include the following: </p>
</li>
<li>XmlOptions.setErrorListener -- Specifies a Collection instance that XMLBeans should use to store errors that occur during validation (or, in other contexts, during parsing and compilation). </li>
<li>XmlOptions.setValidateTreatLaxAsSkip -- Tells XMLBeans that it should skip elements matching an particle with contentModel=&quot;lax&quot; during validation. </li>
</ul>
<p>Also, see the <a href="#validation_as_you_go">section on validating as you go</a> for information about using the <code>XmlOptions.setValidateOnSet</code> method.</p>
<h3><a name="retrieving_error_messages" id="retrieving_error_messages"></a>Retrieving Error Messages About Invalid XML</h3>
<p>When you'll be validating with one of the <code>validate</code> methods, you can specify a <code>java.util.Collection</code> implementation as an error listener. As validation occurs, errors are added to the listener. After validation (and if the instance is found to be invalid) you can examine the errors. Here's an example:</p>
<pre>// Set up the validation error listener.
ArrayList validationErrors = new ArrayList();
XmlOptions validationOptions = new XmlOptions();
validationOptions.setErrorListener(validationErrors);
MyDocument myDoc = MyDocument.Factory.parse(pathToXml);
// Do some editing to myDoc.
// During validation, errors are added to the ArrayList for
// retrieval and printing by the printErrors method.
boolean isValid = myDoc.validate(validationOptions);
// Print the errors if the XML is invalid.
if (!isValid)
{
Iterator iter = validationErrors.iterator();
while (iter.hasNext())
{
System.out.println(">> " + iter.next() + "\n");
}
}</pre>
<h3><a name="validation_as_you_go" id="validation_as_you_go"></a>Validation As You Go</h3>
<p>By default, an XML instance will not be validated at run time as your code makes changes. However, you can change this behavior for limited on-the-fly validation. To do this, you specify the &quot;validate on set&quot; option when you create the XMLBeans type instance &#8212; you do this with the <code>XmlOptions.setValidateOnSet</code> method. </p>
<p>When you specify this option, XMLBeans with throw an exception when your code invalidates the XML through a set* method. Note that you can't specify an error listener for use in conjunction with this means of validating. Also, with &quot;validate on set,&quot; only simple schema types will be validated. Schema types not validated by this approach include, for example, those defining elements with attributes or elements with children.</p>
<p>Because its functionality is limited to simple schema types and it validates for set* method calls, you should regard this validation approach as a debugging tool, rather than an alternative to using a <code>validate</code> method. For example, you might use it to determine which errant bit of code is creating an invalid chunk of XML.</p>
<p class="notepara"><strong>Note:</strong> This sort of validation is not supported during changes you make using an <code>XmlCursor</code> instance.</p>
<p>Among the methods you can use to create an XMLBeans instance &#8212; the <code>parse</code> methods and the <code>newInstance</code> method &#8212; you'll find versions that take an <code>XmlOptions</code> instance as a parameter. Specifying this option would look something like the following: </p>
<pre>XmlOptions validateOptions = new XmlOptions();
// Tell XMLBeans you want to validate on the fly.
validateOptions.setValidateOnSet();
// Create the new instance, specifying the option.
PurchaseOrder newPo = PurchaseOrder.Factory.newInstance(validateOptions);
// ... Code to edit the instance via get and set methods ... </pre>
<div>
<p class="relatedtopics"> Related Topics </p>
<p> <a href="conGettingStartedwithXMLBeans.html">Getting Started with XMLBeans</a> </p>
</div>
<!-- InstanceEndEditable -->
<script language="JavaScript">
</script>
</body>
</html>