public class XMLUtil {
public static Document parseXML(String xml) throws ParserConfigurationException, IOException, SAXException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setExpandEntityReferences(false);
factory.setValidating(false);
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
documentBuilder.setErrorHandler(new ErrorHandler() {
public void error(SAXParseException exception) throws SAXException {
throw new RuntimeException(exception.toString());
}
public void fatalError(SAXParseException exception) throws SAXException {
throw new RuntimeException(exception.toString());
}
public void warning(SAXParseException exception) throws SAXException {
System.out.println(exception.getMessage());
}
});
return documentBuilder.parse(new InputSource(new StringReader(xml)));
}
public static String toString(Document document) throws TransformerException {
Transformer t = newIndentingTransformer();
StringWriter resultWriter = new StringWriter();
Result result = new StreamResult(resultWriter);
t.transform(new DOMSource(document), result);
return resultWriter.toString();
}
public static String toString(Node node) throws TransformerException {
Transformer t = newIndentingTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter resultWriter = new StringWriter();
Result result = new StreamResult(resultWriter);
t.transform(new DOMSource(node), result);
return resultWriter.toString();
}
private static Transformer newIndentingTransformer() throws TransformerConfigurationException {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty(OutputKeys.METHOD, "xml");
t.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml");
return t;
}
}