<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You 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.
-->
<!DOCTYPE document PUBLIC "-//APACHE//DTD Documentation V2.0//EN" "http://forrest.apache.org/dtd/document-v20.dtd">
<document>
    <header>
        <title>Validation with XMLBeans</title>
    </header>
    <body>
        <section>
            <title>Validation with XMLBeans</title>
            <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>
        </section>

        <section>
            <title>Validation, XMLBeans-Style</title>
            <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>
        </section>

        <section>
            <title>>XMLBeans Validates Only When You Ask It To &#8212; Generally</title>
            <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>
            <note>
                <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.
            </note>
        </section>

        <section id="no_parsing_validation">
            <title>XMLBeans Does Not Validate an Instance While Parsing It</title>
            <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>
            <source><![CDATA[
                MyXmlSchemaType myXmlBean = MyXmlSchemaType.Factory.parse(myXml);
            ]]></source>
            <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 "low bar"
                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 "validate on set" option.</li>
                <li>Using one of the command-line tools.</li>
            </ul>
        </section>

        <section>
            <title>Tools for Validating</title>
            <p>XMLBeans tools for validation include command-line tools and APIs.</p>

            <section id="command_line_validation">
                <title>Command-line Tools for Validation</title>
                <p>Among the many <a href="site:tools">command-line tools</a> XMLBeans provides, you'll find two that
                    are specifically for validation.
                </p>
                <ul>
                    <li>
                        <a href="site:tools/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="site:tools/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>
            </section>

            <section id="validation_apis">
                <title>APIs for Validation</title>
                <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>
            </section>

            <section id="validation_when_you_ask">
                <title>Validation When You Ask for It</title>
                <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="lax" 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>
            </section>
        </section>

        <section id="retrieving_error_messages">
            <title>Retrieving Error Messages About Invalid XML</title>
            <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>
            <source><![CDATA[
                // 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");
                    }
                }
            ]]></source>
        </section>

        <section id="validation_as_you_go">
            <title>Validation As You Go</title>
            <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 "validate on
                set" 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 "validate on set," 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>
            <note>
                <strong>Note:</strong>
                This sort of validation is not supported during changes you make using an <code>XmlCursor</code> instance.
            </note>
            <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>
            <source><![CDATA[
                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 ...
            ]]></source>
        </section>

        <section id="relatedtopics">
            <title>Related Topics</title>
            <p>
                <a href="site:gettingstarted">Getting Started with XMLBeans</a>
            </p>
        </section>
    </body>
</document>