Java Reference
In-Depth Information
Use the javax.xml.stream.XMLStreamReader interface to read documents.
Using this API, your code will pull XML elements using a cursor-like interface similar
to that in SQL to process each element in turn. The following code snippet from
org.java8recipes.DocReader demonstrates how to read the patients.xml
file that was generated in the previous recipe:
public void cursorReader(String xmlFile)
throws FileNotFoundException, IOException,
XMLStreamException {
XMLInputFactory factory
= XMLInputFactory.newFactory();
try (FileInputStream fis = new
FileInputStream(xmlFile)) {
XMLStreamReader reader
= factory.createXMLStreamReader(fis);
boolean inName = false;
boolean inDiagnosis = false;
String id = null;
String name = null;
String diagnosis = null;
while (reader.hasNext()) {
int event = reader.next();
switch (event) {
case XMLStreamConstants.START_ELEMENT:
String elementName
= reader.getLocalName();
switch (elementName) {
case "patient":
id
= reader.getAttributeValue(0);
break;
case "name":
inName = true;
break;
case "diagnosis":
inDiagnosis = true;
break;
Search WWH ::




Custom Search