Generated classes will have two methods for decoding:
public void decodeDocument(javax.xml.stream.XMLStreamReader reader) public void decode(javax.xml.stream.XMLStreamReader reader, boolean asGroup)
The decodeDocument
method should be used when the parser is positioned at the start of an XML document,
making it necessary to move to the root element before reaching the data to be decoded. This is the method
you will most likely use.
The decode
method should be used when the parser is already positioned on the element to be decoded.
If the current element contains the content to be decoded, invoke decode
with asGroup = false
.
If, however, the current element is itself part of the content to be decoded (and, in some cases, its siblings also), then
invoke decode
with asGroup = true
. Most likely, you will pass false
.
To illustrate, suppose that we have a SEQUENCE
type that defines elem1
and elem2
.
If we have an XML snippet to decode, <root><elem1/><elem2/></root>
, and we are positioned on the root
element, we would use asGroup = false
, because root
contains the content to be decoded and is not a part of it.
If, however, we were positioned on the elem1
element, we would use group = true
, because elem1
is a part of the content to be decoded; it is the beginning of the content itself.
The general procedure for decoding is as follows:
Create an XMLInputFactory
.
Configure the factory to do coalescing.
Get a new XMLStreamReader
from the factory.
Instantiate an instance of the generated class you want to decode.
Invoke the decodeDocument
method on the generated class.
Access the decoded data through the public members of the generated class.
A program fragment that could be used to decode an employee record is as follows:
public class Reader { public static void main (String args[]) { String filename = "message.xml"; java.io.InputStream inputFile = null; try { // Create an XML reader object inputFile = new java.io.BufferedInputStream( new java.io.FileInputStream(filename) ); javax.xml.stream.XMLInputFactory xmlInputFactory = javax.xml.stream.XMLInputFactory.newInstance(); xmlInputFactory.setProperty( javax.xml.stream.XMLInputFactory.IS_COALESCING, Boolean.TRUE); javax.xml.stream.XMLStreamReader reader = xmlInputFactory.createXMLStreamReader(inputFile); // Read and decode the message PersonnelRecord personnelRecord = new PersonnelRecord (); personnelRecord.decodeDocument(reader); if (trace) { System.out.println ("Decode was successful"); personnelRecord.print (System.out, "personnelRecord", 0); } } catch (Exception e) { System.out.println (e.getMessage()); e.printStackTrace(); System.exit(-1); } finally { if ( inputFile != null ) try { inputFile.close(); } catch (java.io.IOException e) {} } } }