Java xml to string write xml file

ww‮figi.w‬tidea.com

To write XML data to a file in Java, you can use the javax.xml.transform.Transformer class. Here's an example that shows how to write an XML document to a file:

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;

public class XMLWriter {

    public static void writeXmlToFile(Document doc, String filePath) throws Exception {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(filePath);
        transformer.transform(source, result);
    }

    public static void main(String[] args) throws Exception {
        // create a sample document
        Document doc = createSampleDocument();

        // write the document to a file
        writeXmlToFile(doc, "output.xml");
    }

    private static Document createSampleDocument() throws Exception {
        // create a new document
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

        // create the root element
        Element rootElement = doc.createElement("root");
        doc.appendChild(rootElement);

        // add some child elements
        Element childElement1 = doc.createElement("child1");
        childElement1.setTextContent("value1");
        rootElement.appendChild(childElement1);

        Element childElement2 = doc.createElement("child2");
        childElement2.setTextContent("value2");
        rootElement.appendChild(childElement2);

        return doc;
    }

}

This code creates an XML document and writes it to a file named "output.xml" in the current working directory. The writeXmlToFile method takes a Document object and a file path, and uses a Transformer object to write the XML data to the file. The createSampleDocument method is a helper method that creates a sample XML document for testing purposes.