Java tutorial
//package com.java2s; //License from project: Open Source License import org.w3c.dom.Document; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.Reader; import java.io.StringReader; public class Main { public static Document toDocument(String xml) throws Exception { // default we ignore namespaces return toDocument(xml, false); } public static Document toDocument(String xml, boolean namespaceAware) throws Exception { return toDocument(xml, namespaceAware, false); } public static Document toDocument(String xml, boolean namespaceAware, boolean ignoreDtd) throws Exception { Reader input = new StringReader(xml); InputSource is = new InputSource(input); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(namespaceAware); // ignore dtd files if (ignoreDtd) { dbf.setValidating(false); dbf.setFeature("http://xml.org/sax/features/namespaces", false); dbf.setFeature("http://xml.org/sax/features/validation", false); dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); } DocumentBuilder db = dbf.newDocumentBuilder(); db.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { throw exception; } public void fatalError(SAXParseException exception) throws SAXException { throw exception; } public void error(SAXParseException exception) throws SAXException { throw exception; } }); return db.parse(is); } }