Loading...

Create a XML or HTML document

:heavy_exclamation_mark: This post is older than a year. Consider some information might not be accurate anymore. :heavy_exclamation_mark:

Using in Java the Document Object Model (DOM). This post contains a snippet to create XML document object.

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();

To create an XML document from String input

/**
 * Create document from String
 * @param xml
 * @return
 * @throws Exception
 */
public static Document createDocumentFromXMLString(String xml) {
	try {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setNamespaceAware(true);
		DocumentBuilder builder = factory.newDocumentBuilder();
		return builder.parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
	} catch (ParserConfigurationException | IOException | SAXException e) {
		LOGGER.error("Could not create document for input {}", xml, e);
	}
	return null;
}
Please remember the terms for blog comments.