How to Parse XML from a String in Java
When working with XML in Java, it’s common to parse XML from a file using classes like DocumentBuilder and DocumentBuilderFactory. However, there are scenarios where XML needs to be parsed directly from a String
. This article explains two effective methods for converting an XML string into a Document
object: using an InputSource
with a StringReader
and converting the string into an InputStream
.
1. Parsing XML as a String in Java
To parse XML as a String
, the key is to convert the String
into a source that the DocumentBuilder
can process. This article provides two common ways to achieve this:
- Using InputStream: This involves converting the
String
to a byte array, which is then wrapped in aByteArrayInputStream
. - Using InputSource: This wraps the
String
with aStringReader
for theDocumentBuilder
to read.
2. Using InputSource
Here is the first approach, which uses an InputSource
to wrap the XML string:
import org.w3c.dom.Document; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.xml.sax.InputSource; import java.io.StringReader; public class XmlParserWithInputSource { public static Document loadXMLFromString(String xml) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(xml)); return builder.parse(is); } public static void main(String[] args) { String xmlString = "<note><to>John</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>"; try { Document document = loadXMLFromString(xmlString); System.out.println("Root element: " + document.getDocumentElement().getNodeName()); } catch (Exception e) { } } }
In this example, the InputSource
wraps the String
using a StringReader
, allowing the DocumentBuilder
to read it as an input source. The DocumentBuilder.parse()
method then processes the InputSource
and converts it into a DOM Document
.
For the given XML string, this approach generates the following parsed output:
Root element: note
This confirms the XML string was successfully parsed into a DOM Document
.
3. Using InputStream
An alternative approach is to convert the XML string into a ByteArrayInputStream
and parse it:
import org.w3c.dom.Document; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; public class XmlParserWithInputStream { public static Document loadXMLFromString(String xml) throws Exception { InputStream stream = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(stream); } public static void main(String[] args) { String xmlString = "<note><to>John</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>"; try { Document document = loadXMLFromString(xmlString); System.out.println("Root element: " + document.getDocumentElement().getNodeName()); } catch (Exception e) { } } }
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
.
3.1 When to Use Each Approach
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.
4. Conclusion
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
. Both approaches offer simple and efficient ways to work with XML data dynamically, without relying on external files. Depending on your specific needs, whether it is ease of implementation or control over encoding, either method can be an ideal choice for parsing XML in Java.
5. Download the Source Code
This article explores how to parse an XML string in Java.
You can download the full source code of this example here: java parse xml string