Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert org.w3c.dom.Document to File file

Tags:

java

xml

I have a xml file as object in Java as org.w3c.dom.Document doc and I want to convert this into File file. How can I convert the type Document to File? thanks

I want to add metadata elements in an existing xml file (standard dita) with type File. I know a way to add elements to the file, but then I have to convert the file to a org.w3c.dom.Document. I did that with the method loadXML:

private Document loadXML(File f) throws Exception{ 
DocumentBuilder b = DocumentBuilderFactory.newInstance().newDocumentBuilder();
return builder.parse(f);

After that I change the org.w3c.dom.Document, then I want to continue with the flow of the program and I have to convert the Document doc back to a File file.

What is a efficient way to do that? Or what is a better solution to get some elements in a xml File without converting it?

like image 948
jer08 Avatar asked May 08 '16 20:05

jer08


1 Answers

You can use a Transformer class to output the entire XML content to a File, as showed below:

Document doc =...

// write the content into xml file
    DOMSource source = new DOMSource(doc);
    FileWriter writer = new FileWriter(new File("/tmp/output.xml"));
    StreamResult result = new StreamResult(writer);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(source, result);
like image 95
Mario Cairone Avatar answered Oct 18 '22 21:10

Mario Cairone