XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader reader = factory.createXMLStreamReader(new FileInputStream("example.xml")); while (reader.hasNext()) { int event = reader.next(); if (event == XMLStreamConstants.START_ELEMENT) { // process start element if (reader.getLocalName().equals("book")) { // extract data from book element String title = reader.getAttributeValue(null, "title"); String author = reader.getAttributeValue(null, "author"); System.out.println(title + " by " + author); } } }
XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader reader = factory.createXMLStreamReader(new FileInputStream("example.xml")); XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); XMLStreamWriter writer = outputFactory.createXMLStreamWriter(new FileOutputStream("output.xml")); while (reader.hasNext()) { int event = reader.next(); if (event == XMLStreamConstants.START_ELEMENT) { // modify start element if (reader.getLocalName().equals("name")) { writer.writeStartElement(reader.getPrefix(), reader.getLocalName(), reader.getNamespaceURI()); writer.writeAttribute("new-attribute", "value"); } else { writer.writeStartElement(reader.getPrefix(), reader.getLocalName(), reader.getNamespaceURI()); writer.writeAttributes(reader); } } else { writer.writeEvent(event, reader); } } writer.flush(); writer.close();In this example, the isStartElement method is used to determine whether the current event is a start element. If the element is a "name" element, the code adds a new attribute to it before writing it to the output stream. Otherwise, it simply writes the original element as is to the output stream. Overall, XMLStreamReader is an important class for working with XML files and the isStartElement method is a useful tool for navigating through the XML stream.