I try to parse an XML file with a StAX XML-parser. It give me START_ELEMENT
and END_DOCUMENT
events but no ATTRIBUTE
events. How can I receive ATTRIBUTE
events with the StAX parser?
My XML:
<?xml version="1.0" encoding="utf-8"?>
<posts>
<row name="Jonas"/>
<row name="John"/>
</posts>
My StAX XML-parser:
public class XMLParser {
public void parseFile(String filename) {
XMLInputFactory2 xmlif = (XMLInputFactory2) XMLInputFactory2.newInstance();
xmlif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.FALSE);
xmlif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
xmlif.setProperty(XMLInputFactory.IS_COALESCING, Boolean.FALSE);
xmlif.configureForSpeed();
XMLStreamReader2 xmlr = (XMLStreamReader2)
xmlif.createXMLStreamReader(new FileInputStream(filename));
int eventType;
while(xmlr.hasNext()) {
eventType = xmlr.next();
switch(eventType) {
case XMLStreamConstants.START_ELEMENT:
if(xmlr.getName().toString().equals("row")) {
System.out.println("row");
}
break;
case XMLStreamConstants.ATTRIBUTE:
System.out.println("Attribute");
break;
case XMLStreamConstants.END_DOCUMENT:
System.out.println("END");
xmlr.close();
break;
}
}
}
public static void main(String[] args) {
XMLParser p = new XMLParser();
String filename = "data/test.xml";
p.parseFile(filename);
}
}
XMLEventReader reads an XML file as a stream of events. isStartElement(): checks if the current event is a StartElement (start tag) isEndElement(): checks if the current event is an EndElement (end tag) asCharacters(): returns the current event as characters. getName(): gets the name of the current event.
StAX is a PULL API, whereas SAX is a PUSH API. It means in case of StAX parser, a client application needs to ask the StAX parser to get information from XML whenever it needs.
The XMLStreamReader is designed to iterate over XML using next() and hasNext(). The data can be accessed using methods such as getEventType(), getNamespaceURI(), getLocalName() and getText(); The next() method causes the reader to read the next parse event.
The cursor API has two main interfaces: XMLStreamReader for parsing XML and XMLStreamWriter for generating XML.
You can obtain the attributes when you are in the START_ELEMENT
state. See the getAttribute*
methods on XMLStreamReader
:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With