Java tutorial
//package com.java2s; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.InputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; public class Main { public static Document loadXML(String xml) { if (null == xml) { return null; } Document dom = null; InputStream stream = null; try { stream = new ByteArrayInputStream(xml.getBytes("utf-8")); return load(stream); } catch (Exception e) { } finally { try { stream.close(); } catch (Exception e) { } } return dom; } public static Document load(InputStream stream) { try { BufferedInputStream bs = new BufferedInputStream(stream); bs.mark(1); if (-1 == bs.read()) return null; bs.reset(); return newDocumentBuilder().parse(bs); } catch (Exception e) { return null; } } public static Document load(String uri) { Document dom = null; try { DocumentBuilder db = newDocumentBuilder(); dom = db.parse(uri); } catch (Exception e) { } return dom; } private static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException { return newDocumentBuilderFactory().newDocumentBuilder(); } private static DocumentBuilderFactory newDocumentBuilderFactory() { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setIgnoringElementContentWhitespace(true); dbf.setIgnoringComments(true); dbf.setIgnoringElementContentWhitespace(true); dbf.setExpandEntityReferences(false); return dbf; } }