Java tutorial
//package com.java2s; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; public class Main { /** * Reads the events from the provided event stream until either a start or * end tag is encountered. In the former case, the start tag will be * returned, but if an end tag is encountered, <code>null</code> will be * returned. After returning, the stream will be positioned just before the * returned start element. The start element will not be consumed by this * method. * * @param reader The event stream from which to read. * @return The StartElement read from the stream, or <code>null</code> if * an end tag was found first, or the stream ended before a start * element was found. * @throws XMLStreamException If an error occurs reading the stream. */ public static final StartElement nextElement(XMLEventReader reader) throws XMLStreamException { return nextElement(reader, null); } /** * Reads the events from the provided event stream until either a start or * end tag is encountered. In the former case, the start tag will be * returned if it matches the specified QName, but if it doesn't match, an * end tag is encountered, or the stream ends, <code>null</code> will be * returned. After returning, the stream will be positioned just before the * start element. The start element will not be consumed by this method. * * @param reader The event stream from which to read. * @param name The name of the element to read, or <code>null</code> to * read any start tag. * @return The StartElement read from the stream, or <code>null</code> if * the encountered start tag didn't match the specified QName, an * end tag was found first, or the stream ended before a start * element was found. * @throws XMLStreamException If an error occurs reading the stream. */ public static final StartElement nextElement(XMLEventReader reader, QName name) throws XMLStreamException { while (reader.hasNext()) { XMLEvent nextEvent = reader.peek(); if (nextEvent.isStartElement()) { StartElement start = nextEvent.asStartElement(); if (name == null || start.getName().equals(name)) { return start; } else { break; } } else if (nextEvent.isEndElement()) { break; } else { // consume the event. reader.nextEvent(); } } return null; } }