Java Reference
In-Depth Information
}
public
public int
int next () throws
throws XMLStreamException {
int
int state = super
super . next ();
switch
switch ( state ) {
case
case XMLStreamConstants . START_ELEMENT :
... process the start element looking for
for Item ID ...
break
break ;
case
case XMLStreamConstants . CHARACTERS :
... if item id , save the characters .
break
break ;
}
return
return state ;
}
}
Next, associate this reader with the input stream that the Validator object will use:
SchemaFactory sf = SchemaFactory . newInstance (
XMLConstants . W3C_XML_SCHEMA_NS_URI );
StreamSource ss = new
new StreamSource ( rp . getSchemaFileName ());
Schema schema = sf . newSchema ( new
new Source []{ ss });
XMLInputFactory staxFactory = XMLInputFactory . newInstance ();
staxFactory . setProperty ( XMLInputFactory . IS_VALIDATING , Boolean . FALSE );
XMLStreamReader xsr = staxFactory . createXMLStreamReader ( ins );
XMLStreamReader reader = new
new MyXMLStreamReader ( xsr );
Validator validator = schema . newValidator ();
validator . validate ( new
new StAXSource ( new
new StaxSource ( reader )));
The validate() method, while performing regular validation, will also call the stream read-
er delegate, which will parse the desired information from the input data (essentially, as a
side effect of validation).
One downside to this approach is that processing cannot be cleanly terminated once the 10
items have been read. The code can still throw an exception from the next() method and
catch that exception later—just as was previously done for the SAXDoneException . The
problem is that the default schema listener will print out an error message during processing
when the exception is thrown.
Table 10-7 shows the effect of all these operations. Compared to simple (nonvalidating) pars-
ing, parsing with the default validation incurs a large penalty. Reusing the schema makes up
Search WWH ::




Custom Search