I have this simplified xml file, in production it will be large one. I have to read info element (id, sender, recipient) and I am doing it successfully using stream API with XMLEventReader, XMLEvent jdk classes. I am also reading car data like owner, I have to save owner to database, similar to info data. But there is more about car data..
Second part of my task is to take each car node and save it to database as CLOB, one record per car. With XMLEventReader I am not able to do it because I don't have whole xml context and current car XMLEvent does not have something like toString method serializing the whole xml part to text. I would also not like to recreate XML structure by myself. I am wondering how to do that in most efficient way and not load the whole XML into memory. Maybe reading info should be one part and second part of the parser would be to peek specific nodes and cut them out from stream somehow even without reading the car data itself, and save each car to database ? Is it possible somehow in Java 8+ ?
<message>
<info>
<id>123</id>
<sender>
<name>dorothy</name>
</sender>
<recipient>
<name>dorothy</name>
</recipient>
</info>
<car>
<owner>adam1</owner>
</car>
<car>
<owner>adam2</owner>
</car>
<car>
<owner>adam3</owner>
</car>
</message>
</root>
EDIT:
I am able to divide xml into parts:
FileInputStream fis = new FileInputStream(entry.toFile());
XMLStreamReader xmlr = xmlif.createXMLStreamReader(fis);
int eventType = xmlr.getEventType();
printEventType(eventType);
while (xmlr.hasNext()) {
eventType = xmlr.next();
if (xmlr.isStartElement() && xmlr.getLocalName().equals("car")) {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
File file = new File("out" + System.currentTimeMillis() + ".xml");
t.transform(new StAXSource(xmlr), new StreamResult(file));
//printAttributes(xmlr);
//
} else if (xmlr.isStartElement()){
printName(xmlr, eventType); //elements of car nodes are not present, propalby consumed by above if statement
}