Java tutorial
//package com.java2s; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.xml.sax.SAXException; public class Main { /** * Loads an XML document from an InputStream */ public static Document loadXmlDoc(final InputStream stream) { Document result = null; try { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setExpandEntityReferences(false); domFactory.setIgnoringComments(true);//strips comments // domFactory.setIgnoringElementContentWhitespace(true);//would be nice if it worked domFactory.setNamespaceAware(true); DocumentBuilder builder = domFactory.newDocumentBuilder(); result = builder.parse(stream); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } /** * Loads an XML document from a File * @param uri The path the file. */ public static Document loadXmlDoc(final String uri) { Document result = null; try { File file = new File(uri); if (file.exists()) { result = loadXmlDoc(new FileInputStream(file)); } else { throw new IOException("File does not exist: " + file.getAbsolutePath()); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } }