Java
XML Parsing
String Manipulation
Programming
Coding Tutorial

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:

  1. Convert the String to an InputStream: Since the parsers typically work with InputStreams or Readers, you'll first need to convert your XML string to an InputStream.
  2. Create a DocumentBuilder Instance: DocumentBuilderFactory and DocumentBuilder are used to parse XML documents in Java.
  3. Parse the InputStream to obtain a Document: You can parse the InputStream which contains the XML content to create a Document object.

Here’s a sample code snippet:

java
1import javax.xml.parsers.DocumentBuilder;
2import javax.xml.parsers.DocumentBuilderFactory;
3import org.w3c.dom.Document;
4import java.io.ByteArrayInputStream;
5
6public class XMLStringParser {
7    public static void main(String[] args) throws Exception {
8        String xml = "<note><to>Reader</to><from>Author</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>";
9        ByteArrayInputStream input = new ByteArrayInputStream(xml.getBytes("UTF-8"));
10
11        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
12        DocumentBuilder builder = factory.newDocumentBuilder();
13        
14        Document doc = builder.parse(input);
15        System.out.println("Root element: " + doc.getDocumentElement().getNodeName());
16    }
17}

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:

  1. Create a SAXParser Instance: Obtain an instance of SAXParser from SAXParserFactory.
  2. Define a Handler: Implement handlers by extending DefaultHandler to define actions upon events like start and end of an element.
  3. Parse the XML content: Convert your XML string into an InputStream and parse it.

Here's an example:

java
1import javax.xml.parsers.SAXParser;
2import javax.xml.parsers.SAXParserFactory;
3import org.xml.sax.Attributes;
4import org.xml.sax.helpers.DefaultHandler;
5import java.io.ByteArrayInputStream;
6
7public class SAXExample extends DefaultHandler {
8    public void startElement(String uri, String localName, String qName, Attributes attributes) {
9        System.out.println("Start Element: " + qName);
10    }
11
12    public void characters(char ch[], int start, int length) {
13        System.out.println("Characters: " + new String(ch, start, length));
14    }
15
16    public void endElement(String uri, String localName, String qName) {
17        System.out.println("End Element:" + qName);
18    }
19
20    public static void main(String[] args) throws Exception {
21        String xml = "<note><to>Reader</to>hello<from>Author</from></note>";
22        ByteArrayInputStream input = new ByteArrayInputStream(xml.getBytes());
23        SAXParserFactory factory = SAXParserFactory.newInstance();
24        SAXParser saxParser = factory.newSAXParser();
25        SAXExample handler = new SAXExample();
26        saxParser.parse(input, handler);
27    }
28}

Summary Table

APIDescriptionProsCons
DOMLoads the complete XML document as a tree structure.Easy to navigate and modify.Consumes more memory.
SAXParses 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.


Course illustration
Course illustration

All Rights Reserved.