XmlBeans Tutorial / Mixed Content

XML Schema

This tutorial aims to show how to manipulate the following XML Schema code snippet, which contains mixed content type, with Apache XMLBeans:-

{{{<xsd:element name="field">

</xsd:element> <xsd:element name="fieldArray">

</xsd:element>}}} The FieldArray type is essentially an array of Field types. The Field type is a mixed
content complex type. When this schema is compiled using XMLBeans it creates a
number of classes:-

* FieldArrayDocument with a FieldArray inner class i.e. FieldArrayDocument.FieldArray
* FieldDocument with a Field innerclass i.e. FieldDocument.Field

XML Document Creation

No Mixed Content

To create a Field element within the FieldArrayDocument.FieldArray, with a name attribute set to the string Foo, and no body content:-

Code

{{{FieldArrayDocument fieldArrayDocument = FieldArrayDocument.Factory.newInstance(); FieldArrayDocument.FieldArray fieldArray = fieldArrayDocument.addNewFieldArray(); FieldDocument.Field field = fieldArray.addNewField(); Field.setName(“Foo”);}}}

Output

{{{<FieldArray>

</FieldArray>}}}

Mixed Content

To create a similar result with the body of the Field set to 5.

Code

{{{// Create the FieldArrayDocument, FieldArray and Field exactly as we did the first time FieldArrayDocument fieldArrayDocument = FieldArrayDocument.Factory.newInstance(); FieldArrayDocument.FieldArray fieldArray = fieldArrayDocument.addNewFieldArray(); FieldDocument.Field field = fieldArray.addNewField(); // We now have our field in the fieldArray but we need to set the attribute and body content // We create the cursor on the FieldDocument.Field not on the FieldDocument XmlCursor lXmlCursor = field.newCursor(); // Move the cursor to the first point we can insert any values lXmlCursor.toFirstContentToken(); // Set the name attribute to be Foo lXmlCursor.insertAttributeWithValue("name", “Foo”); // Set the body text between the start and end Field tags to the string 5 lXmlCursor.insertChars(“5”); // Finish with the cursor the Field is now complete lXmlCursor.dispose(); // Now add a field with no body to the same FieldArrayDocument field = fieldArray.addNewField(); // This will be the second element in the FieldArray with a name of Foo2 and no body content field.setName(“Foo2”); }}}

Output

{{{<FieldArray>

</FieldArray>}}}

That’s all there is to mixing the use of the XmlCursor in with the normal addxxx(), getxxx() and setxxx() methods on an XMLBeans generated java object.

Written by Don dot Stewart at grian dot ltd dot uk

XmlBeansTutorial/MixedContent (last edited 2009-09-20 23:34:19 by localhost)