Programming : Creating a Document from a String in Java

This page last changed on Sep 12, 2006 by Kees de Kooter

W3C method

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class Documents {

    public static Document createFromString(String xml) {
        
        Document document = null;
        
        try {
            DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().
                newDocumentBuilder();
            document = documentBuilder.parse(
                    new InputSource(new StringReader(xml)));
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        return document;
    }
}

dom4j method

    public static Document createFromString(String xml) {
        
        Document document = null;
        
        try {
            SAXReader xmlReader = new SAXReader(false);
            org.dom4j.Document dom4jDocument = xmlReader.read(
                    new StringReader(xml));
            
            DOMWriter domWriter = new DOMWriter();
            document = domWriter.write(dom4jDocument);
        } catch (DocumentException e) {
            log.error(e.toString(), e);
        }
        
        return document;
    }