ok, i have code which works on this xml:
1
abcdef
2
abcdef
abcdef
The code splits initial XML file into 2 files, and also tries to add some tags afterwards.
import java.io.*;
import java.io.FileReader;
import java.io.FileWriter;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stax.StAXResult;
import javax.xml.transform.stream.StreamResult;
import javax.xml.stream.XMLStreamException;
import java.io.FileOutputStream;
import javax.xml.transform.OutputKeys;
public class ver2 {
public static void main(String[] args) throws Exception {
XMLInputFactory xif = XMLInputFactory.newInstance();
xif.setProperty("javax.xml.stream.isCoalescing", true);
XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("out.xml"));
XMLOutputFactory factory = XMLOutputFactory.newInstance();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
xsr.nextTag();
int i=0;
while(xsr.hasNext()) {
int event = xsr.next();
if (event== XMLStreamConstants.START_ELEMENT){
if (xsr.getLocalName().equals("record")){
i++;
File file = new File(i + ".txt");
try {
XMLStreamWriter writer = factory.createXMLStreamWriter(new FileWriter(file));
t.transform(new StAXSource(xsr), new StAXResult(writer));
writer.writeStartElement("addSomeTags");
writer.writeCharacters("\r\n");
writer.writeStartElement("somestuff");
writer.writeEndElement();
writer.writeEndElement();
writer.flush();
writer.close();
} catch (XMLStreamException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
The problem is that when i open resulting files in notepad, notepad doesn't recognize linebreak characters. (probably because they are "/n", not "/n/r") At the same time if i transformed StaxSource into StreamResult (not employing XMLStreamWriter) notepad would recognize them. Can you explain why it happens, and, how to make it well-formated?
(but as you understand it IS presented properly in wordPad or other text Editors including this one)
Also, if this way is perverse in some way, please, let me know.
解决方案
Change code from
writer.writeCharacters("\r\n");
to
write.writeCharacters(System.getProperty("line.separator"));
This is more generic and should work better
than \r\n which would only work on windows.