Write an xml dom to a xml file
I have got the xml to print in the system, but I want to have that printed into a .xml file, how do I do that? Here is what I got so far
Code Java:
import javax.xml.stream.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import java.io.*;
public class XMLWriter {
public static void main(String[] args) throws XMLStreamException {
File xmlFile = new File("file.xml");
try{
Document document;
FileWriter fstream = new FileWriter(xmlFile);
BufferedWriter out = new BufferedWriter(fstream);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
// Create an output factory
XMLOutputFactory xmlof = XMLOutputFactory.newInstance();
// Create an XML stream writer
XMLStreamWriter xmlw = xmlof.createXMLStreamWriter(System.out);
xmlw.writeStartDocument();
xmlw.writeDTD("<!DOCTYPE file SYSTEM \"file.dtd\">");
xmlw.writeStartElement("file");
xmlw.writeEmptyElement("filename");
xmlw.writeAttribute("filename", "ReadMe.txt");
xmlw.writeEmptyElement("keyword");
xmlw.writeAttribute("keyword", "Some word to match");
xmlw.writeEmptyElement("option");
xmlw.writeAttribute("option", "matchcase");
// Write document end. This closes all open structures
xmlw.writeEndDocument();
// Close the writer to flush the output
xmlw.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Re: Write an xml dom to a xml file
See a) the API for XMLOutputFactory - the method createXMLStreamWriter takes an OutputStream to write to (currently you are using System.out) b) See FileOutputStream (Java Platform SE 6). In other words, create a FileOutputStream and pass this instead of System.out
Re: Write an xml dom to a xml file
Ah perfect thank you for that it worked fine all I had to do was this
XMLStreamWriter xmlw = xmlof.createXMLStreamWriter(new FileOutputStream("file.xml"));
and all better ^:)^