Java tutorial
//package com.java2s; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.events.XMLEvent; import javax.xml.stream.util.XMLEventConsumer; public class Main { /** * Skips all events within a <code>StartElement</code> until the matching * <code>EndElement</code> is reached. This method assumes that the reader * is positioned after the <code>StartElement</code> event, and when the * method completes, the stream will be positioned before the * <code>EndElement</code> event, but it will not consume the end tag. * * @param reader The event stream to read, positioned after the * <code>StartElement</code> * @throws XMLStreamException If an error occurs reading events. */ public static final void skipElementContent(XMLEventReader reader) throws XMLStreamException { copyElementContent(reader, null); } /** * Skips an element's complete content. This method assumes that the * <code>START_ELEMENT</code> has already be passed, and when it terminates, * the stream will be positioned at the <code>END_ELEMENT</code>. * * @param reader The stream reader to read. * @throws XMLStreamException If an error occurs reading the stream. */ public static final void skipElementContent(XMLStreamReader reader) throws XMLStreamException { int depth = 0; while (depth >= 0) { reader.next(); if (reader.isStartElement()) { depth++; } else if (reader.isEndElement()) { depth--; } } } /** * Copies all events within a <code>StartElement</code> until the matching * <code>EndElement</code> is reached. This method assumes that the reader * is positioned after the <code>StartElement</code> event, and when the * method completes, the stream will be positioned before the * <code>EndElement</code> event, but it will not consume the end tag. * * @param reader The event stream to read, positioned after the * <code>StartElement</code> * @param consumer The destination for events read from teh stream, or * <code>null</code> to ignore the events completely. * @throws XMLStreamException If an error occurs reading events. */ public static final void copyElementContent(XMLEventReader reader, XMLEventConsumer consumer) throws XMLStreamException { if (!reader.hasNext()) return; for (int depth = 1; true;) { // peek and see if we're at the end element XMLEvent currEvt = reader.peek(); if (currEvt.isEndElement()) { depth--; if (depth == 0) { break; } } else if (currEvt.isStartElement()) { depth++; } // consume the event currEvt = reader.nextEvent(); if (consumer != null) { consumer.add(currEvt); } } } }