Link to home
Start Free TrialLog in
Avatar of Testsubbu
Testsubbu

asked on

Fileoutput stream to write out an xml file

Dear java experts,
               
 I have an xml as STRING  created
<a>
    <b>test<b>
</a>

How do I write this out to an XML File in a Desired location , I have the path.
thanks,
testsubbu
ASKER CERTIFIED SOLUTION
Avatar of Nick_72
Nick_72

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Nick_72
Nick_72

BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("C:\\your\\path\\yourfile.xml")));
Avatar of CEHJ
Try something like:



String s = "<a><b>test<b></a>";

..........


public static void writeXmlFile(String xmlString, String filename) {
        try {
            // Prepare the xml for writing
            Source source = new StreamSource(new StringReader(xmlString));
   
            // Prepare the output file
            File file = new File(filename);
            Result result = new StreamResult(file);
   
            // Write the DOM document to the file
            Transformer xformer = TransformerFactory.newInstance().newTransformer();
            xformer.transform(source, result);
        } catch (TransformerConfigurationException e) {
        } catch (TransformerException e) {
        }
    }


You can't use OutputStreams or even Writers as if the input were to contain certain characters, they would not get handled correctly for the purposes of xml.
Testsubbu, as i've explained that answer is not correct. It may well work in the case that you've posted, but if you used it to write the following:

String s = "<a><b>1 & 1 == true<b></a>";

The only time you'll find out it doesn't work is when you try to read the resulting file with any xml classes