Java SE API
DocumentBuilder.parse()
Parse XML using configured parser settings; syntax errors are reported as SAXException. Java SE API; example uses Java 21-compatible syntax.
Formal Syntax & Structure
java syntaxjava
Document parse(InputSource is)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| is | InputSource | XML source |
Return Value
Document
Parse XML using configured parser settings; syntax errors are reported as SAXException.
Working Example
Example Snippetjava
import java.util.*;import java.util.regex.*;import java.nio.*;import java.nio.charset.*;import java.io.*;import javax.xml.XMLConstants;import javax.xml.parsers.*;import org.xml.sax.*;import org.xml.sax.helpers.DefaultHandler;import org.w3c.dom.*;public class Main { static Document parse(String xml) throws Exception { if (xml.length() > 4096) throw new IllegalArgumentException("document too long"); var f = DocumentBuilderFactory.newDefaultInstance(); f.setNamespaceAware(true); f.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); f.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); f.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); f.setXIncludeAware(false); f.setExpandEntityReferences(false); var b = f.newDocumentBuilder(); b.setErrorHandler(new DefaultHandler() { @Override public void error(SAXParseException e) throws SAXException { throw e; } @Override public void fatalError(SAXParseException e) throws SAXException { throw e; } }); return b.parse(new InputSource(new StringReader(xml))); } public static void main(String[] args) throws Exception { var doc = parse("<item code=\"AB12\"><name>Tea & Cake</name><qty>7</qty></item>"); var item = doc.getDocumentElement(); System.out.println(item.getTagName()); System.out.println(item.getAttribute("code")); System.out.println(item.getElementsByTagName("name").item(0).getTextContent()); }}