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);
}
}
You can obtain the attributes when you are in the START_ELEMENT
state. See the getAttribute*
methods on XMLStreamReader
: