下面列出了怎么用javax.xml.stream.util.StreamReaderDelegate的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Returns a XML stream reader over only a portion of the document, from given position inclusive
* until the end of the given element exclusive. Nested elements of the same name, if any, will be
* ignored.
*
* @param tagName name of the tag to close.
* @return a reader over a portion of the stream.
* @throws XMLStreamException if this XML reader has been closed.
*/
protected final XMLStreamReader getSubReader(final QName tagName) throws XMLStreamException {
return new StreamReaderDelegate(reader) {
/** Increased every time a nested element of the same name is found. */
private int nested;
/** Returns {@code false} if we reached the end of the sub-region. */
@Override public boolean hasNext() throws XMLStreamException {
return (nested >= 0) && super.hasNext();
}
/** Reads the next element in the sub-region. */
@Override public int next() throws XMLStreamException {
if (nested < 0) {
throw new NoSuchElementException();
}
final int t = super.next();
switch (t) {
case START_ELEMENT: if (tagName.equals(getName())) nested++; break;
case END_ELEMENT: if (tagName.equals(getName())) nested--; break;
}
return t;
}
};
}
private XMLStreamReader createNoCDATAReader(final XMLStreamReader reader) {
return new StreamReaderDelegate(reader) {
public int next() throws XMLStreamException {
int i = super.next();
return i == XMLStreamConstants.CDATA ? XMLStreamConstants.CHARACTERS : i;
}
};
}
/**
* Creates a new reader for the given source.
* It is caller's responsibility to close the given stream reader after usage
* (it will <strong>not</strong> be done by {@link XMLEventReader#close()}).
*
* @param in where to read from.
* @return the reader.
* @throws XMLStreamException if the reader can not be created.
*/
public static XMLEventReader createXMLEventReader(final XMLStreamReader in) throws XMLStreamException {
return FACTORY.createXMLEventReader(new StreamReaderDelegate(in) {
@Override public void close() throws XMLStreamException {
// Do not close the XMLStreamReader because user may continue reading from it.
}
});
}