Overview | Package | Class | Tree | Deprecated | Index | Help
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

## org.apache.xmlbeans
Interface XmlObject

All Superinterfaces:
  XmlTokenSource

All Known Subinterfaces:
  SimpleValue, XmlAnySimpleType, XmlAnyURI, XmlBase64Binary, XmlBoolean, XmlByte, XmlDate, XmlDateTime, XmlDecimal, XmlDouble, XmlDuration, XmlENTITIES, XmlENTITY, XmlFloat, XmlGDay, XmlGMonth, XmlGMonthDay, XmlGYear, XmlGYearMonth, XmlHexBinary, XmlID, XmlIDREF, XmlIDREFS, XmlInt, XmlInteger, XmlLanguage, XmlLong, XmlName, XmlNCName, XmlNegativeInteger, XmlNMTOKEN, XmlNMTOKENS, XmlNonNegativeInteger, XmlNonPositiveInteger, XmlNormalizedString, XmlNOTATION, XmlPositiveInteger, XmlQName, XmlShort, XmlString, XmlTime, XmlToken, XmlUnsignedByte, XmlUnsignedInt, XmlUnsignedLong, XmlUnsignedShort

All Known Implementing Classes:
  FilterXmlObject

public interface XmlObject
extends XmlTokenSource

Corresponds to the XML Schema xs:anyType, the base type for all XML Beans.

Since all XML Schema types are translated into corresponding XML Bean classes, and all Schema type derivation corresponds to Java class inheritance, the fact that all Schema types derive from xs:anyType means that all XML Bean classes derive from XmlObject.

On this base class you will find a number of common facilities that all XML Bean classes provide:

- Every XML Bean class has an inner Factory class for creating and parsing instances, including XmlObject. Use `XmlObject.Factory` itself to produce untyped XML trees or XML trees that implement specific subtypes of XmlObject depending on a recognized root document element. If you depend on the automatic type inference, you will want to understand the type inference issues described below.
- To write out an accurate XML file for the XML tree under this XmlObject, use one of the `XmlTokenSource.save(org.xml.sax.ContentHandler, org.xml.sax.ext.LexicalHandler)` methods, or `XmlTokenSource.newInputStream()` or `XmlTokenSource.newReader()`. Use `toString()` to produce a pretty-printed representation of the XML subtree under this XML Object. If you save interior portions of an XML document, you will want to understand the inner contents versus outer container issues described below.
- It is also simple to copy an XmlObject instance to or from a standard DOM tree or SAX stream. Use `XmlObject.Factory.parse(Node)`, for example, to load from DOM; use `XmlObject.Factory.newXmlSaxHandler()` to load from SAX; use `XmlTokenSource.newDomNode()` to save to DOM; and use `XmlTokenSource.save(org.xml.sax.ContentHandler, org.xml.sax.ext.LexicalHandler)` to save to SAX.
- Use `validate()` to validate the subtree of XML under this XML Object. If you wish to get information about the location and reason for validation errors, see `XmlOptions.setErrorListener(java.util.Collection)`, and use `validate(XmlOptions)`.
- Use `XmlTokenSource.newCursor()` to access the full XML infoset, for example, if you need to determine interleaved element order or manipulate annotations, comments, or mixed content. You can get an element name with a cursor by calling `cursor.getName()` when the cursor is positioned at an element's START token. See `XmlCursor`.
- Use `selectPath(java.lang.String)` to find other XmlObjects in the subtree underneath this XmlObject using relative XPaths. (In selectPath, "." indicates the current element or attribute.)

Type inference. When using `XmlObject.Factory` to parse XML documents, the actual document type is not `type` itself, but a subtype based on the contents of the parsed document. If the parsed document contains a recognized root document element, then the actual type of the loaded instance will be the matching Document type. For example:

     XmlObject xobj = XmlObject.Factory.parse(myDocument);
     if (xobj instanceof MyOrderDocument) // starts w/ <my-order>
     {
         MyOrderDocument mydoc = (MyOrderDocument)xobj;
         if (!xobj.validate())
             System.out.println("Not a valid my-order document");
     }
     else
     {
         System.out.println("Not a my-order document");
     }

Every XML Bean class has its own inner Factory class, so if you actually know exactly which XML Bean document type you want to load as in the example above, you should use the the specific XML Bean Factory class instead. For example:

     MyOrderDocument mydoc = MyOrderDocument.Factory.parse(myDocument);

The code above will throw an exception if the parsed document does not begin with the proper (my-order) element.

Inner versus outer. An XmlObject represents the contents of an element or attribute, not the element or attribute itself. So when you validate or save an XmlObject, you are validating or saving its contents, not its container. For example, if the XmlObject represents the contents of an element which happens to itself be in the wrong order relative to its siblings, validate will not complain about the misplacement of the element itself. On the other hand, if elements within the XmlObject are in the wrong order, validate will complain. Similarly, when saving the contents of an interior XmlObject, it is the contents of an element, not the element itself, which is saved by default.

Reading and writing fragments. When reading or writing the contents of a whole XML document, the standard XML reprentation for a document is used. However, there is no standard concrete XML representation for "just the contents" of an interior element or attribute. So when one is needed, the tag <xml-fragment> is used to wrap the contents. This tag is used can also be used to load just the contents for an XmlObject document fragment of arbitrary type. If you wish to save out the XmlObject's container element along with its contents, use `XmlOptions.setSaveOuter()`.

Implementing XmlObject. The XMLBeans library does not support arbitrary implementations of XmlObject - in almost all cases, you should only use the implementations of XmlObject provided by the XMLBeans compiler itself. If you need to implement XmlObject yourself, you should subclass FilterXmlObject in order to delegate to another underlying XmlObject implementation. This technique will allow you to use your code unchanged with future versions of XMLBeans that add additional methods on XmlObject.

Nested Class Summary
`static class` | `XmlObject.Factory` Static factory class for creating new instances.

Field Summary
`static int` | `EQUAL` EQUAL is 0.
`static int` | `GREATER_THAN` GREATER_THAN is 1.
`static int` | `LESS_THAN` LESS_THAN is -1.
`static int` | `NOT_EQUAL` NOT_EQUAL is 2.
`static SchemaType` | `type` The constant `SchemaType` object representing this schema type.

Method Summary
`XmlObject` | `changeType(SchemaType newType)` Changes the schema type associated with this data and returns a new XmlObject instance whose schemaType is the new type.
`int` | `compareTo(Object obj)` Impelements the Comparable interface by comparing two simple xml values based on their standard XML schema ordering.
`int` | `compareValue(XmlObject obj)` This comparison method is similar to compareTo, but rather than throwing a ClassCastException when two values are incomparable, it returns the number 2.
`XmlObject` | `copy()` Returns a deep copy of this XmlObject.
`XmlObject[]` | `execQuery(String query)` Executes a query.
`XmlObject[]` | `execQuery(String query, XmlOptions options)` Executes a query with options.
`boolean` | `isImmutable()` True if the value is an immutable value.
`boolean` | `isNil()` True if the value is nil.
`SchemaType` | `schemaType()` The schema type for this instance.
`XmlObject` | `selectAttribute(QName attributeName)` Selects the content of the attribute with the given name.
`XmlObject` | `selectAttribute(String attributeUri, String attributeLocalName)` Selects the content of the attribute with the given name.
`XmlObject[]` | `selectAttributes(QNameSet attributeNameSet)` Selects the contents of the attributes that are contained in the elementNameSet.
`XmlObject[]` | `selectChildren(QName elementName)` Selects the contents of the children elements with the given name.
`XmlObject[]` | `selectChildren(QNameSet elementNameSet)` Selects the contents of the children elements that are contained in the elementNameSet.
`XmlObject[]` | `selectChildren(String elementUri, String elementLocalName)` Selects the contents of the children elements with the given name.
`XmlObject[]` | `selectPath(String path)` Selects a path.
`XmlObject[]` | `selectPath(String path, XmlOptions options)` Selects a path, applying options.
`XmlObject` | `set(XmlObject srcObj)` Set the value/type of this XmlObject to be a copy of the source XmlObject.
`void` | `setNil()` Sets the value to nil.
`XmlObject` | `substitute(QName newName, SchemaType newType)` Changes the schema type associated with this data using substitution groups and returns an XmlObject instance whose schemaType is the new type and container name is the new name.
`String` | `toString()` Returns an XML string for this XML object.
`boolean` | `validate()` Returns true if the contents of this object are valid accoring to schemaType().
`boolean` | `validate(XmlOptions options)` Just like validate(), but with options.
`boolean` | `valueEquals(XmlObject obj)` True if the xml values are equal.
`int` | `valueHashCode()`

Methods inherited from interface org.apache.xmlbeans.XmlTokenSource
`documentProperties, dump, getDomNode, monitor, newCursor, newDomNode, newDomNode, newInputStream, newInputStream, newReader, newReader, newXMLInputStream, newXMLInputStream, newXMLStreamReader, newXMLStreamReader, save, save, save, save, save, save, save, save, xmlText, xmlText`

Field Detail

### type

    public static final SchemaType type

  The constant `SchemaType` object representing this schema type.

### LESS_THAN

    public static final int LESS_THAN

  LESS_THAN is -1. See `compareValue(org.apache.xmlbeans.XmlObject)`.

  See Also:
    Constant Field Values

### EQUAL

    public static final int EQUAL

  EQUAL is 0. See `compareValue(org.apache.xmlbeans.XmlObject)`.

  See Also:
    Constant Field Values

### GREATER_THAN

    public static final int GREATER_THAN

  GREATER_THAN is 1. See `compareValue(org.apache.xmlbeans.XmlObject)`.

  See Also:
    Constant Field Values

### NOT_EQUAL

    public static final int NOT_EQUAL

  NOT_EQUAL is 2. See `compareValue(org.apache.xmlbeans.XmlObject)`.

  See Also:
    Constant Field Values

Method Detail

### schemaType

    public SchemaType schemaType()

  The schema type for this instance. This is a permanent, unchanging property of the instance.

### validate

    public boolean validate()

  Returns true if the contents of this object are valid accoring to schemaType().

  Does a deep validation of the entire subtree under the object, but does not validate the parents or siblings of the object if the object is in the interior of an xml tree.

### validate

    public boolean validate(XmlOptions options)

  Just like validate(), but with options.

  If you wish to collect error messages and locations while validating, use the `XmlOptions.setErrorListener(java.util.Collection)` method. With that method, you can specify an object in which to store messages related to validation. The following is a simple example.

       // Create an XmlOptions instance and set the error listener.
       XmlOptions validateOptions = new XmlOptions();
       ArrayList errorList = new ArrayList();
       validateOptions.setErrorListener(errorList);

       // Validate the XML.
       boolean isValid = newEmp.validate(validateOptions);

       // If the XML isn't valid, loop through the listener's contents,
       // printing contained messages.
       if (!isValid)
       {
            for (int i = 0; i < errorList.size(); i++)
            {
                XmlError error = (XmlError)errorList.get(i);

                System.out.println("\n");
                System.out.println("Message: " + error.getMessage() + "\n");
                System.out.println("Location of invalid XML: " +
                    error.getCursorLocation().xmlText() + "\n");
            }
       }

  Parameters:
    `options` - An object that implements the `Collection` interface.

### selectPath

    public XmlObject[] selectPath(String path)

  Selects a path. Path can be a string or precompiled path String.

  The path must be a relative path, where "." represents the element or attribute containg this XmlObject, and it must select only other elements or attributes. If a non-element or non-attribute is selected, an unchecked exception is thrown.

  The array that is returned contains all the selected XmlObjects, within the same document, listed in document order. The actual array type of the result is inferred from the closest common base type of selected results.

  Here is an example of usage. Suppose we have a global element definition for "owner" whose type is "person":

         <schema targetNamespace="http://openuri.org/sample">
            <element name="owner" type="person"/>
            <complexType name="person">
               [...]
            </complexType>
         </schema>

  and suppose "owner" tags can be scattered throughout the document. Then we can write the following code to find them all:

       import org.openuri.sample.Person;
       import org.apache.xmlbeans.*;
       [...]
         XmlObject xobj = XmlObject.Factory.parse(myFile);
         Person[] results;
         results = (Person[])xobj.selectPath(
            "declare namespace s='http://www.openuri.org/sample' " +
            ".//s:owner");

  Notice the way in which namespace declarations are done in XPath 2.0. Since XPath can only navigate within an XML document - it cannot construct new XML - the resulting XmlObjects all reside in the same XML document as this XmlObject itself.

### selectPath

    public XmlObject[] selectPath(String path,
                                  XmlOptions options)

  Selects a path, applying options.

  See Also:
    `selectPath(String)`

### execQuery

    public XmlObject[] execQuery(String query)

  Executes a query. Query can be a string or precompiled query String.

  An XQuery is very similar to an XPath, except that it also permits construction of new XML. As a result, the XmlObjects that are returned from execQuery are in newly created documents, separate from the XmlObject on which the query is executed.

  Syntax and usage is otherwise similar to selectPath.

  See Also:
    `selectPath(String)`

### execQuery

    public XmlObject[] execQuery(String query,
                                 XmlOptions options)

  Executes a query with options. Use the options parameter to specify the following:

  To specify this | Use this method
  --- | ---
  The document type for the root element. | `XmlOptions.setDocumentType(org.apache.xmlbeans.SchemaType)`
  To replace the document element with the specified QName when constructing the resulting document. | `XmlOptions.setLoadReplaceDocumentElement(javax.xml.namespace.QName)`
  To strip all insignificant whitespace when constructing a document. | `XmlOptions.setLoadStripWhitespace()`
  To strip all comments when constructing a document. | `XmlOptions.setLoadStripComments()`
  To strip all processing instructions when constructing a document. | `XmlOptions.setLoadStripProcinsts()`
  A map of namespace URI substitutions to use when constructing a document. | `XmlOptions.setLoadSubstituteNamespaces(java.util.Map)`
  Additional namespace mappings to be added when constructing a document. | `XmlOptions.setLoadAdditionalNamespaces(java.util.Map)`
  To trim the underlying XML text buffer immediately after constructing a document, resulting in a smaller memory footprint. | `XmlOptions.setLoadTrimTextBuffer()`
  Whether value facets should be checked as they are set. | `XmlOptions.setValidateOnSet()`

  Parameters:
    `query` - The XQuery expression.
    `options` - Options as described.
  See Also:
    `execQuery(String)`

### changeType

    public XmlObject changeType(SchemaType newType)

  Changes the schema type associated with this data and returns a new XmlObject instance whose schemaType is the new type.

  Returns the new XmlObject if the type change was successful, the old XmlObject if no changes could be made.

  Certain type changes may be prohibited in the interior of an xml tree due to schema type system constraints (that is, due to a parent container within which the newly specified type is not permissible), but there are no constraints at the roottype changes are never prohibited at the root of an xml tree.

  If the type change is allowed, then the new XmlObject should be used rather than the old one. The old XmlObject instance and any other XmlObject instances in the subtree are permanently invalidated and should not be used. (They will return XmlValueDisconnectedException if you try to use them.) If a type change is done on the interior of an Xml tree, then xsi:type attributes are updated as needed.

### substitute

    public XmlObject substitute(QName newName,
                                SchemaType newType)

  Changes the schema type associated with this data using substitution groups and returns an XmlObject instance whose schemaType is the new type and container name is the new name.

  Returns the new XmlObject if the substitution was successful, the old XmlObject if no changes could be made.

  In order for the operation to succeed, several conditions must hold:
  - the container of this type must be an element
  - a global element with the name `newName` must exist and must be in the substition group of the containing element
  - the `newType` type must be consistent with the declared type of the new element

  If the type change is allowed, then the new XmlObject should be used rather than the old one. The old XmlObject instance and any other XmlObject instances in the subtree are permanently invalidated and should not be used. (They will return XmlValueDisconnectedException if you try to use them.) If necessary, xsi:type attributes are updated.

### isNil

    public boolean isNil()

  True if the value is nil. Note that in order to be nil, the value must be in an element, and the element containing the value must be marked as nillable in the schema.

### setNil

    public void setNil()

  Sets the value to nil. The element containing the value must be marked as nillable in the schema.

### toString

    public String toString()

  Returns an XML string for this XML object.

  The string is pretty-printed. If you want a non-pretty-printed string, or if you want to control options precisely, use the xmlText() methods.

  Note that when producing XML any object other than very root of the document, then you are guaranteed to be looking at only a fragment of XML, i.e., just the contents of an element or attribute, and and we will produce a string that starts with an `<xml-fragment>` tag. The XmlOptions.setSaveOuter() option on xmlText can be used to produce the actual element name above the object if you wish.

### isImmutable

    public boolean isImmutable()

  True if the value is an immutable value. Immutable values do not have a position in a tree; rather, they are stand-alone simple type values. If the object is immutable, the equals() methods tests for value equality, and the object can be used as the key for a hash.

### set

    public XmlObject set(XmlObject srcObj)

  Set the value/type of this XmlObject to be a copy of the source XmlObject. Because the type of the source may be different than this target, this XmlObject may become defunct. In this case the new XmlObject is returned. If no type change happens, the same this will be returned.

### copy

    public XmlObject copy()

  Returns a deep copy of this XmlObject. The returned object has the same type as the current object, and has all the content of the XML document underneath the current object. Note that any parts of the XML document above or outside this XmlObject are not copied.

### valueEquals

    public boolean valueEquals(XmlObject obj)

  True if the xml values are equal. Two different objects (which are distinguished by equals(obj) == false) may of course have equal values (valueEquals(obj) == true).

  Usually this method can be treated as an ordinary equvalence relation, but actually it is not is not transitive. Here is a precise specification:

  There are two categories of XML object: objects with a known instance type, and objects whose only known type is one of the ur-types (either AnyType or AnySimpleType). The first category is compared in terms of logical value spaces, and the second category is compared lexically.

  Within each of these two categories, valueEquals is a well-behaved equivalence relation. However, when comparing an object of known type with an object with ur-type, the comparison is done by attempting to convert the lexical form of the ur-typed object into the other type, and then comparing the results. Ur-typed objects are therefore treated as lexical wildcards and may be equal to objects in different value spaces, even though the objects in different value spaces are not equal to each other.

  For example, the anySimpleType value "1" will compare as an equalValue to the string "1", the float value "1.0", the double value "1.0", the decimal "1", and the GYear "1", even though all these objects will compare unequal to each other since they lie in different value spaces. Note: as of XMLBeans 2.2.1 only implemented for simple type values.

### valueHashCode

    public int valueHashCode()

### compareTo

    public int compareTo(Object obj)

  Impelements the Comparable interface by comparing two simple xml values based on their standard XML schema ordering. Throws a ClassCastException if no standard ordering applies, or if the two values are incomparable within a partial order.

### compareValue

    public int compareValue(XmlObject obj)

  This comparison method is similar to compareTo, but rather than throwing a ClassCastException when two values are incomparable, it returns the number 2. The result codes are -1 if this object is less than obj, 1 if this object is greater than obj, zero if the objects are equal, and 2 if the objects are incomparable.

### selectChildren

    public XmlObject[] selectChildren(QName elementName)

  Selects the contents of the children elements with the given name.

  Parameters:
    `elementName` - The name of the elements to be selected.
  Returns:
    Returns the contents of the selected elements.

### selectChildren

    public XmlObject[] selectChildren(String elementUri,
                                      String elementLocalName)

  Selects the contents of the children elements with the given name.

  Parameters:
    `elementUri` - The URI of the elements to be selected.
    `elementLocalName` - The local name of the elements to be selected.
  Returns:
    Returns the contents of the selected elements.

### selectChildren

    public XmlObject[] selectChildren(QNameSet elementNameSet)

  Selects the contents of the children elements that are contained in the elementNameSet.

  Parameters:
    `elementNameSet` - Set of element names to be selected.
  Returns:
    Returns the contents of the selected elements.
  See Also:
    `SchemaType.qnameSetForWildcardElements()`, `for creating sets of qnames`

### selectAttribute

    public XmlObject selectAttribute(QName attributeName)

  Selects the content of the attribute with the given name.

  Parameters:
    `attributeName` - The name of the attribute to be selected.
  Returns:
    Returns the contents of the selected attribute.

### selectAttribute

    public XmlObject selectAttribute(String attributeUri,
                                     String attributeLocalName)

  Selects the content of the attribute with the given name.

  Parameters:
    `attributeUri` - The URI of the attribute to be selected.
    `attributeLocalName` - The local name of the attribute to be selected.
  Returns:
    Returns the content of the selected attribute.

### selectAttributes

    public XmlObject[] selectAttributes(QNameSet attributeNameSet)

  Selects the contents of the attributes that are contained in the elementNameSet.

  Parameters:
    `attributeNameSet` - Set of attribute names to be selected.
  Returns:
    Returns the contents of the selected attributes.
  See Also:
    `SchemaType.qnameSetForWildcardAttributes()`, `for creating sets of qnames`

Overview | Package | Class | Tree | Deprecated | Index | Help
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD