XML
StAX
Read XML
Common methods of the XMLStreamReader object
Method | Description |
---|---|
hasNext() | Returns true if there are more parsing events and false if there aren't. |
next() | Gets the next parsing event. |
getEventType() | Returns an int value that indicates the type of the parsing event (based on the constants defined by the XMLStreamConstants interface). |
getLocalName() | Returns the name of the current element. |
getAttributeValue(index) | Returns a string value for the attribute stored at the index. |
getAttributeCount() | Returns a count of attributes for this element. |
getAttributeLocalName(index) | Returns the name of the attribute at the specified index. |
getElementText() | Reads the value of a text-only element. An exception is thrown if the element isn't a text-only element. |
getText() | Reads the value of a COMMENT, DTD, CHARACTERS, CDATA, or SPACE parsing event. |
Common constants defined by the XMLStreamConstants interface
Constant | Description |
---|---|
START_ELEMENT | The event is a start element. |
END_ELEMENT | The event is an end element. |
ATTRIBUTE | The event is an attribute |
CHARACTERS | The event is character data. |
COMMENT | The event is a comment. |
SPACE | The event is whitespace. |
DTD | The event is a DTD. |
Code that reads all Product elements into a products array list
ArrayListproducts = new ArrayList (); Product p = null; while (reader.hasNext()) { int eventType = reader.getEventType(); switch (eventType) { case XMLStreamConstants.START_ELEMENT: String elementName = reader.getLocalName(); if (elementName.equals("Product")) { p = new Product(); String code = reader.getAttributeValue(0); p.setCode(code); } if (elementName.equals("Description")) { String description = reader.getElementText(); p.setDescription(description); } if (elementName.equals("Price")) { String priceString = reader.getElementText(); double price = Double.parseDouble(priceString); p.setPrice(price); } break; case XMLStreamConstants.END_ELEMENT: elementName = reader.getLocalName(); if (elementName.equals("Product")) { products.add(p); } break; default: break; } reader.next(); }
A safer and more flexible way to read attributes
int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { if (reader.getAttributeLocalName(i).equals("Code")) { String code = reader.getAttributeValue(i); } }