Java tutorial
//package com.java2s; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.XMLEvent; public class Main { /** * Print this tag and its contents. This will consume everything up to the * matching end tag. * * @param start * @param xml * @param indent * @throws XMLStreamException */ public static String printEvents(XMLEvent current, XMLEventReader xml) throws XMLStreamException { return printEvents(current, xml, 0); } private static String printEvents(XMLEvent start, XMLEventReader xml, int indent) throws XMLStreamException { String ret = "\n"; for (int i = 0; i < indent; i++) { ret += " "; } ret += start + "\n"; XMLEvent next = null; // Keep processing events... while (xml.hasNext()) { next = xml.nextEvent(); // Delegate start tags to a new indentation level if (next.isStartElement()) { printEvents(next, xml, indent + 4); } else if (next.isEndElement()) { // We've found our end element. Add it and be done. for (int i = 0; i < indent; i++) { ret += " "; } ret += next + "\n"; return ret; } else if (next.isCharacters() && next.asCharacters().isWhiteSpace()) { // Skip whitespace continue; } else { // Print the contents of this tag for (int i = 0; i < indent + 4; i++) { ret += " "; } ret += next + "\n"; } } // Oh wow, we ran out of XML. Uh, return then? return ret; } /** * Calls xml.nextEvent() and unchecks the exception. * * @param xml * @return xml.nextEvent(), or throws a RuntimeException. */ public static XMLEvent nextEvent(XMLEventReader xml) { try { return xml.nextEvent(); } catch (XMLStreamException e) { throw new RuntimeException(e); } } public static boolean isWhitespace(XMLEvent e) { if (e.isCharacters() && e.asCharacters().isWhiteSpace()) { return true; } return false; } }