Here you can find the source of stringToDocument(String string)
Parameter | Description |
---|---|
string | the string representing the XML Document |
public static Document stringToDocument(String string) throws IOException, SAXException, ParserConfigurationException
//package com.java2s; //License from project: LGPL import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; public class Main { /**/*from w ww . j a v a2 s . co m*/ * Creates an XML {@link Document} from the given String. * * @param string the string representing the XML {@link Document} * @return a XML Document representation of the given string */ public static Document stringToDocument(String string) throws IOException, SAXException, ParserConfigurationException { return streamToDocument(new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8))); } /** * Creates an XML {@link Document} from the given {@link InputStream}. * * @param stream the XML input stream * @return Document the document created from the stream * @throws IOException if the stream cannot be read or does not contains valid XML content or the XML parser cannot * be configured */ public static Document streamToDocument(InputStream stream) throws IOException { return streamToDocument(stream, null); } /** * Creates an XML {@link Document} from the given {@link InputStream}. * * @param stream the XML input stream * @param resolver is a {@link EntityResolver} to specify how entities given in the {@link Document} should be * resolved * @return Document the document created from the stream * @throws IOException if the stream cannot be read or does not contains valid XML content or the XML parser cannot * be configured */ public static Document streamToDocument(InputStream stream, EntityResolver resolver) throws IOException { DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); DocumentBuilder parser; try { parser = fac.newDocumentBuilder(); if (resolver != null) parser.setEntityResolver(resolver); return parser.parse(new InputSource(stream)); } catch (ParserConfigurationException | SAXException e) { throw new IOException(e); } } }