In Java, how do I parse XML as a String instead of a file?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Parsing XML from a string in Java rather than from a file is a common requirement in scenarios where the XML content is dynamically generated or received from web services, APIs, or stored in databases. Java provides several ways to parse XML, among which DOM (Document Object Model), SAX (Simple API for XML), and StAX (Streaming API for XML) are the most widely used. In this article, we'll focus on how to use these APIs to parse XML content directly from a string.
Parsing XML with DOM
The DOM parser loads the entire XML document into memory as a tree structure, allowing you to access any part of the document repeatedly and modify the tree (if necessary). Here's how you can parse an XML string using DOM:
- Convert the String to an InputStream: Since the parsers typically work with
InputStreamsorReaders, you'll first need to convert your XML string to anInputStream. - Create a DocumentBuilder Instance:
DocumentBuilderFactoryandDocumentBuilderare used to parse XML documents in Java. - Parse the InputStream to obtain a Document: You can parse the
InputStreamwhich contains the XML content to create aDocumentobject.
Here’s a sample code snippet:
Parsing XML with SAX
SAX is an event-driven model which means it doesn't load the entire XML document into memory. Instead, it triggers events as it reads through the XML string. This makes SAX much more memory-efficient, particularly for large XML files.
To use SAX to parse an XML string, follow these steps:
- Create a SAXParser Instance: Obtain an instance of
SAXParserfromSAXParserFactory. - Define a Handler: Implement handlers by extending
DefaultHandlerto define actions upon events like start and end of an element. - Parse the XML content: Convert your XML string into an
InputStreamand parse it.
Here's an example:
Summary Table
| API | Description | Pros | Cons |
| DOM | Loads the complete XML document as a tree structure. | Easy to navigate and modify. | Consumes more memory. |
| SAX | Parses XML as a series of events. | Efficient memory utilization. | Unidirectional parsing, not suitable for modifications. |
Additional Considerations
While both DOM and SAX are standard parsers, Java also supports StAX which combines the benefits of the DOM and SAX approaches. StAX allows reading and writing XML in a streaming way, which is useful for large XML files or streams of XML data.
In conclusion, parsing XML from a string in Java is straightforward with varied approaches depending on the specific requirements of memory efficiency, ease of use, and the need for modifying the XML content after parsing. Depending on your scenario, you may choose DOM for simplicity and direct access to the document, SAX for lower memory footprint, or StAX for a balance of both.

