How to catch event attributes using the StAX XML parser?

I am trying to parse an XML file using the StAX XML parser. It gives me START_ELEMENT and END_DOCUMENT events, but not ATTRIBUTE events. How can I receive ATTRIBUTE events using the StAX analyzer?

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); } } 
+6
source share
2 answers

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

+4
source

All ATTRIBUTEs are even weird, and as Blaise noted, they are not reported separately when using the event-based interface. This is because attributes are a “part” of the start element and must be processed as such using parsers (to verify uniqueness, bind namespaces, etc.).

+3
source

Source: https://habr.com/ru/post/897415/


All Articles