Java tutorial
//package com.java2s; // Licensed to the Apache Software Foundation (ASF) under one import java.io.ByteArrayInputStream; import java.io.File; 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.InputSource; import org.xml.sax.SAXException; public class Main { public static Document parse(String xmlContent) throws IOException { ByteArrayInputStream is = new ByteArrayInputStream(xmlContent.getBytes("UTF-8")); return parse(is); } public static Document parse(File file) throws IOException { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setCoalescing(true); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); factory.setNamespaceAware(true); DocumentBuilder parser = factory.newDocumentBuilder(); return parser.parse(file); } catch (ParserConfigurationException e) { throw new IOException(e); } catch (SAXException e) { throw new IOException(e); } } public static Document parse(InputStream is) throws IOException { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setCoalescing(true); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); factory.setNamespaceAware(true); DocumentBuilder parser = factory.newDocumentBuilder(); InputSource in = new InputSource(is); return parser.parse(in); } catch (ParserConfigurationException e) { throw new IOException(e); } catch (SAXException e) { throw new IOException(e); } } }