Reputation:
I was trying to convert a text file into xml file but then I am having a small trouble while parsing.
This is the code for converting txt file to xml.
public class ToXML {
BufferedReader in;
StreamResult out;
TransformerHandler th;
AttributesImpl atts;
public static void main(String args[]) {
new ToXML().doit();
}
public void doit() {
try {
in = new BufferedReader(new FileReader("E:/Java Codes/JMartin.txt"));
out = new StreamResult("E:/Java Codes/JMartin2.xml");
initXML();
String str;
while ((str = in.readLine()) != null) {
process(str);
}
in.close();
closeXML();
} catch (IOException | ParserConfigurationException | TransformerConfigurationException | SAXException e) {
}
}
public void initXML() throws ParserConfigurationException,
TransformerConfigurationException, SAXException {
SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory
.newInstance();
th = tf.newTransformerHandler();
Transformer serializer = th.getTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
serializer.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount", "4");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
th.setResult(out);
th.startDocument();
atts = new AttributesImpl();
th.startElement("", "", "Author", atts);
}
public void process(String s) throws SAXException {
String[] elements = s.split("<>;");
atts.clear();
th.startElement("", "", "Data", atts);
th.startElement("", "", "AuthorName", atts);
th.characters(elements[0].toCharArray(), 0, elements[0].length());
th.endElement("", "", "AuthorName");
th.endElement("", "", "Data");
}
public void closeXML() throws SAXException {
th.endElement("", "", "Author");
th.endDocument();
}
}
During compilation the code runs just fine, but how can I save the .xml file in my drive?
Any ideas? please help.
Upvotes: 2
Views: 256
Reputation: 5552
You can use a FileWriter
to export the XML document into a XML file.
public void saveTo(Document document, File file) {
try (Writer writer = new FileWriter(file)) {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
/*
* Customize your transformer here:
* - Indentation
* - Encoding
* - ...
*/
transformer.transform(new DOMSource(document), new StreamResult(writer));
}
}
Upvotes: 1