I'd use Java's XML document libraries. It's a bit of a mess, but works.

String xml = "<response>\n" +
             "<returnCode>-2</returnCode>\n" +
             "<error>\n" +
             "<errorCode>100</errorCode>\n" +
             "<errorMessage>ERROR HERE!!!</errorMessage>\n" +
             "</error>\n" +
             "</response>";
Document doc = DocumentBuilderFactory.newInstance()
                                     .newDocumentBuilder()
                                     .parse(new InputSource(new StringReader(xml)));

NodeList errNodes = doc.getElementsByTagName("error");
if (errNodes.getLength() > 0) {
    Element err = (Element)errNodes.item(0);
    System.out.println(err.getElementsByTagName("errorMessage")
                          .item(0)
                          .getTextContent());
} else { 
        // success
}
Answer from azz on Stack Overflow
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-convert-string-to-xml-document-and-xml-document-to-string
Java Convert String to XML Document and XML Document to String | DigitalOcean
August 3, 2022 - String convertDocumentToString(Document doc): This method will take input as Document and convert it to String. We will use Transformer, StringWriter and StreamResult for this purpose. package com.journaldev.xml; import java.io.StringReader; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.tran
🌐
Mkyong
mkyong.com › home › java › java – convert string to xml
Java - Convert String to XML - Mkyong.com
July 29, 2022 - This example shows how to use a JDOM2 parser to convert a String to an XML document and back to a String. ... <dependency> <groupId>org.jdom</groupId> <artifactId>jdom2</artifactId> <version>2.0.6</version> </dependency> ... package com.mkyong.xml.tips; import org.jdom2.Document; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import javax.xml.XMLConstants; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; // JDOM2 Parser public class ConvertStringToXmlJDom2 { final stat
🌐
Baeldung
baeldung.com › home › java › java string › parse xml as a string in java
Parse XML as a String in Java | Baeldung
August 15, 2025 - In this tutorial, we’ll discuss how to convert an XML string to an XML document. In particular, we’ll cover two approaches to the problem. Then, we’ll discuss how to parse an XML file into a Java String object.
🌐
Java Code Geeks
javacodegeeks.com › home › core java
How to Parse XML from a String in Java - Java Code Geeks
November 18, 2024 - In this example, the ByteArrayInputStream converts the String into bytes and wraps it in a stream, which is then passed to the DocumentBuilder. The DocumentBuilder.parse() method reads the InputStream and generates a DOM Document. InputSource: Use when working with small, well-defined XML strings and you want a straightforward solution. InputStream: Use when encoding is critical or when the XML string is generated from byte-based sources. In this article, we explored two effective methods for parsing XML from a String in Java: using an InputSource with a StringReader and converting the String into an InputStream.
🌐
How to do in Java
howtodoinjava.com › home › java xml › java convert string to xml dom example
Java Convert String to XML DOM Example
September 3, 2023 - To get the XML dom from XML file, instead of passing the XML string to DocumentBuilder, pass the file path to let the parser read the file content directly. We have employees.xml file which has XML content, we will read to get XML document. <employees> <employee id="101"> <name>Lokesh Gupta</name> <title>Author</title> </employee> <employee id="102"> <name>Brian Lara</name> <title>Cricketer</title> </employee> </employees> import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; public class StringtoXMLExample
🌐
Json2CSharp
json2csharp.com › code-converters › xml-to-java
Convert XML to JAVA Object Online - Json2CSharp Toolkit
Here's how you can convert your XML string to Java objects or POJO classes, we will be using the converter and built in libraries like 'com.fasterxml.jackson.dataformat' to parse our object.
🌐
Baeldung
baeldung.com › home › java › java string › convert an xml object to a string in java
Convert an XML Object to a String in Java | Baeldung
June 20, 2025 - In this tutorial, we’ll discuss several ways of transforming an XML Document object into a string in Java. ... Document document = // ... This Document object represents XML content in memory: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <root> <child1>This is child element 1</child1> <child2>This is child element 2</child2> </root> Now, we need to convert this XML Document object into a Java string.
Find elsewhere
Top answer
1 of 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);
}
2 of 4
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

🌐
DaniWeb
daniweb.com › programming › software-development › threads › 394788 › string-to-xml-object-java
string to xml object java | DaniWeb
Note: @JamesCherrill’s concatenation approach creates a correct XML string but the stub wants Axis MessageElement content; @Aviras’s JDOM suggestion is also workable if you convert JDOM to a DOM Element or MessageElement before setting the bean. ... String data = ..... String dataXML = "<MGWData>" + data + "</MGWData>"; — JamesCherrill 4,733 Jump to Post · Look up JDom, it's a java developed XML parser and writer API.
🌐
Coderanch
coderanch.com › t › 512978 › java › convert-string-xml-file-java
How to convert string to xml file in java (Java in General forum at Coderanch)
October 8, 2010 - If you have the XML in a string, and you want it in a file, then the only thing you have to do is save the string into a file. No need to use the XML parsing API. ... Thanks jespar.. :-) ... Hopefully you will find the answer here Create XML using Java DOM you can find the java source code ...
🌐
Blogger
javarevisited.blogspot.com › 2015 › 07 › how-to-read-xml-file-as-string-in-java-example.html
How to Read XML File as String in Java? 3 Examples
May 16, 2023 - If you use any XML library or even XML parser like DOM and SAX, you don't need to make any additional adjustment, they will take care of reading String incorrect encoding, but if you use BufferedReader or any general Stream reader, you must ensure that correct character encoding is used. In this article, you will learn three ways to read XML files as String in Java, first by using FileReader and BufferedReader, second by using DOM parser, and third by using open-source XML library jcabi-xml.
🌐
ServiceNow Community
servicenow.com › community › developer-forum › how-do-i-convert-xml-object-to-string-requirement-is-to-replace › m-p › 2093269
How do I convert XML object to String ? Requirement is: to replace < and > with < and > respectively and make the string back to XML format. Sample XML is shown as below.
June 11, 2018 - ... Mark Correct if this solves your issue and also hit Like and Helpful if you find my response worthy based on the impact. Thanks Ankur · Regards, Ankur Certified Technical Architect || 9x ServiceNow MVP || ServiceNow Community Leader ... replace works only with String, the Xml in question ...
🌐
Oracle
forums.oracle.com › ords › apexds › post › how-to-parse-whole-xml-elements-into-a-java-string-0709
how to parse whole xml elements into a java String - Oracle Forums
January 17, 2008 - hello everybody, I am trying to parse whole xml into a string for example my xml file is as below: ---------------------------------
🌐
Oracle
forums.oracle.com › ords › apexds › post › string-to-xml-object-java-1417
string to xml object java - Oracle Forums
November 17, 2011 - Hello, can anyone suggest me how to convert string to xml object in java? I have a string (Data) ant now I have to pass it as parameter as xml object, which structure should be: Data&l...
🌐
IBM
ibm.com › docs › en › bpm › 8.5.7
Java to XML conversion
We cannot provide a description for this page right now
🌐
How to do in Java
howtodoinjava.com › home › java xml › java convert xml to string – write xml dom to a file
Java Convert XML to String - Write XML Dom to a File
March 9, 2023 - StringWriter writer = new StringWriter(); //transform document to string transformer.transform(new DOMSource(xmlDocument), new StreamResult(writer)); return writer.getBuffer().toString(); } catch (TransformerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; } private static void writeXmlDocumentToFile(Document xmlDocument, String fileName) { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer; try { transformer = tf.newTransformer(); //Uncomment if you do not require XML declaration //transformer.setOutputProperty(Outp