Java examples for XML:XMLEventReader
get Item from XML String using StAX parser
import java.io.StringReader; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; public class Main{ public static void main(String[] argv) throws Exception{ String line = "java2s.com"; String element = "java2s.com"; System.out.println(getItem(line,element)); }/*from w w w . jav a2 s .c om*/ public static String getItem(String line, String element) throws XMLStreamException { String title = null; XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); XMLEventReader xmlEventReader = xmlInputFactory .createXMLEventReader(new StringReader(line)); while (xmlEventReader.hasNext()) { XMLEvent xmlEvent = xmlEventReader.nextEvent(); if (xmlEvent.isStartElement()) { StartElement startElement = xmlEvent.asStartElement(); if (startElement.getName().getLocalPart() .equalsIgnoreCase("row")) { title = getStringElement(startElement, element); } } } xmlEventReader.close(); return title; } public static String getStringElement(StartElement startElement, String elementName) { Attribute bodyAttr = startElement.getAttributeByName(new QName( elementName)); String body = null; if (bodyAttr != null) body = bodyAttr.getValue(); return body; } }