Convert org.w3c.dom.Document file to file

I have an XML file as an object in Java as org.w3c.dom.Document doc, and I want to convert it to a File file. How can I convert a document type to a file? thank

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

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

After that I change org.w3c.dom.Document, then I want to continue the program and I need to convert the Document document back to File.

What is an effective way to do this? Or what is the best solution to get some elements into an XML file without converting it?

+9
source share
2 answers

You can use the Transformer class to output all XML content to a file, as shown 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);
+10
source

With JDK 1.8.0, you can use the built-in XMLSerializer (which was introduced in JDK 1.4 as a branch of Apache Xerces).

import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

Document doc = //use your method loadXML(File f)

//change Document

java.io.Writer writer = new java.io.FileWriter("MyOutput.xml");
XMLSerializer xml = new XMLSerializer(writer, null);
xml.serialize(doc);

Use a type object OutputFormatto configure the output, for example, like this:

OutputFormat format = new OutputFormat(Method.XML, StandardCharsets.UTF_8.toString(), true);
format.setIndent(4);
format.setLineWidth(80);
format.setPreserveEmptyAttributes(true);
format.setPreserveSpace(true);
XMLSerializer xml = new XMLSerializer(writer, format);

Please note that classes from are com.sun.*not documented and therefore are usually not considered as the preferred way of working. However, javax.xml.transform.OutputKeysyou cannot specify, for example, the size of the indentation or the width of the line. So, if this is important, then this solution should help.

0
source

All Articles