Hallo everyone,
I would like to split a XML File with multiple repeated Tag. I found the ideal example in internet and the solution in Java:
Input XML:
Code:
<statements>
<statement account="123">
...stuff...
</statement>
<statement account="456">
...stuff...
</statement>
</statements>
I would like to chunk this one XML File into a list of String for the tag statement:
Code:
<statement account="123">
...stuff...
</statement>
...
...
...
Code:
<statement account="456">
...stuff...
</statement>
The below solution does the main purpose, though each chunk is going to be an independent XML File:
Code:
import java.io.File;
import java.io.FileReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamResult;
public class Demo {
public static void main(String[] args) throws Exception {
XMLInputFactory xif = XMLInputFactory.newInstance();
XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("input.xml"));
xsr.nextTag(); // Advance to statements element
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
while(xsr.nextTag() == XMLStreamConstants.START_ELEMENT) {
File file = new File("out/" + xsr.getAttributeValue(null, "account") + ".xml");
t.transform(new StAXSource(xsr), new StreamResult(file));
}
}
My question or my problem:
I would like to put the chuncks as a list of String. Is there a chance for me to implement this directly? Thank you for the comments.
Regards,
Ratna