How to catch Attribute-events with a StAX XML-parser?
Asked Answered
I

2

7

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);
    }

}
Immunity answered 15/9, 2011 at 18:29 Comment(0)
S
6

You can obtain the attributes when you are in the START_ELEMENT state. See the getAttribute* methods on XMLStreamReader:

Saxena answered 15/9, 2011 at 19:10 Comment(0)
C
4

The whole ATTRIBUTEs even is an odd thing, and as Blaise mentioned, they are not separately reported when using event-based interface. This because attributes are "part of" start element, and need to be handled as such by parsers (to verify uniqueness, bind namespaces etc).

Chuckle answered 16/9, 2011 at 16:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.