10

I am wanting to convert a xml string to a xml file. I am getting a xml string as an out put and I have the following code so far:

public static void stringToDom(String xmlSource) 
    throws SAXException, ParserConfigurationException, IOException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new InputSource(new StringReader(xmlSource)));
        //return builder.parse(new InputSource(new StringReader(xmlSource)));
    }

However Im not too sure where I go from here. I am not creating the file anywhere, so how do I incorporate that into it?

I am passing my xml string into xmlSource.

4 Answers 4

32

If you just want to put the content of a String in a file, it doesn't really matter whether it is actually XML or not. You can skip the parsing (which is a relatively expensive operation) and just dump the String to file, like so:

public static void stringToDom(String xmlSource) 
        throws IOException {
    java.io.FileWriter fw = new java.io.FileWriter("my-file.xml");
    fw.write(xmlSource);
    fw.close();
}

If you want to be on the safe side and circumvent encoding issues, as pointed by Joachim, you would need parsing however. Since its good practice to never trust your inputs, this might be the preferable way. It would look like this:

public static void stringToDom(String xmlSource) 
        throws SAXException, ParserConfigurationException, IOException {
    // Parse the given input
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(xmlSource)));

    // Write the parsed document to an xml file
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);

    StreamResult result =  new StreamResult(new File("my-file.xml"));
    transformer.transform(source, result);
}
Sign up to request clarification or add additional context in comments.

3 Comments

This uses the platform default encoding which can easily result in a malformed XML file. The hard way (as started by the OP) is the safer approach for this.
How would use this method to set the string or value between tags in an xml file? so for instance in an xml file I have the <ExceptionCode></ExceptionCode> and <ExceptionMessage></ExceptionMessage>
builder.parse(new InputSource(new StringReader(xmlSource))); is invalid. (The method parse(InputStream) in the type DocumentBuilder is not applicable for the arguments (InputSource))
2
public static void stringToDom(String xmlSource) throws SAXException, ParserConfigurationException, IOException, TransformerException{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(xmlSource)));
    // Use a Transformer for output
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();

    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File("c:/temp/test.xml"));
    transformer.transform(source, result);
}  

Source : http://docs.oracle.com/javaee/1.4/tutorial/doc/JAXPXSLT4.html

Comments

1

If your XML string is clean and ready to be written, why don't you copy it into a file with .xml at the end ?

With Java 1.7 :

Path pathXMLFile = Paths.get("C:/TEMP/TOTO.XML");
Files.write(pathXMLFile, stringXML.getBytes(), StandardOpenOption.WRITE, StandardOpenOption.APPEND, StandardOpenOption.CREATE);

Easy and quick :)

2 Comments

stringXML.getBytes() get's the bytes in platform default encoding. You should use the same one as used in the xml header here to avoid problems parsing that file later on.
which is the case very seldom.
-1

Just copy the contents of XML string to another file with extension .xml . You can use java.io for the same .

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.