Java read xml stax parser cursor iterator
Here is an example of how to read an XML file using StAX parser in Java:
import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; public class StaxParserExample { public static void main(String[] args) { try { XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader reader = factory.createXMLStreamReader(new FileInputStream("input.xml")); List<Employee> employees = new ArrayList<>(); Employee employee = null; String tagContent = null; while (reader.hasNext()) { int event = reader.next(); switch (event) { case XMLStreamReader.START_ELEMENT: if ("employee".equals(reader.getLocalName())) { employee = new Employee(); employee.id = Integer.parseInt(reader.getAttributeValue(0)); } break; case XMLStreamReader.CHARACTERS: tagContent = reader.getText().trim(); break; case XMLStreamReader.END_ELEMENT: switch (reader.getLocalName()) { case "firstName": employee.firstName = tagContent; break; case "lastName": employee.lastName = tagContent; break; case "email": employee.email = tagContent; break; case "salary": employee.salary = Double.parseDouble(tagContent); break; case "employee": employees.add(employee); break; } break; } } for (Employee emp : employees) { System.out.println(emp); } } catch (FileNotFoundException | XMLStreamException e) { e.printStackTrace(); } } static class Employee { int id; String firstName; String lastName; String email; double salary; @Override public String toString() { return "Employee{" + "id=" + id + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", salary=" + salary + '}'; } } }
In this example, we first create an XMLInputFactory
and use it to create an XMLStreamReader
for the XML file we want to read. We then define some variables to hold the data we will extract from the file. We use a while
loop to iterate over the XML events in the file. We switch on the type of event and extract the data we need. We create a new Employee
object for each employee
element in the file, and add it to a list. Finally, we loop over the list and output the data to the console.
Note that this code may throw exceptions such as FileNotFoundException
and XMLStreamException
, so you should be prepared to handle these exceptions in your code. Also note that this example uses an inner class Employee
to hold the data for each employee, but you could also use a separate class or a Map
to hold this data.