public static String documentToString(Document doc) { return sourceToString(new DOMSource(doc)); } public static String sourceToString(Source source) { try { StringWriter sw = new StringWriter(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.transform(source, new StreamResult(sw)); return sw.toString(); } catch (Exception ex) { throw new RuntimeException("Error converting to String", ex); } } public static Source toSource(String xml){ return new StreamSource(new StringReader(xml)); } public static Document stringToDocument(String xml) { Document doc = null; try { DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); doc = db.parse( new InputSource( new StringReader( xml ) ) ); } catch (Exception e) { throw new RuntimeException("Error converting to String", e); } return doc; } public static Source stringToDocumentToSource(String xml) { return new DOMSource(stringToDocument(xml)); } public static Source stringToSource(String xml) { return new StreamSource(new StringReader(xml)); }
¿Porque es importante el Source?. A la hora de realizar el marshall/unmarshall de objetos y strings JAXB siempre quiere datos de tipo Source.
public Object xmlToObject(String xml) throws Exception { ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes(getEncoding())); StreamSource source = new StreamSource(bais); return xmlToObject(source); } public Object xmlToObject(Source source) throws Exception { return jaxb2Marshaller.unmarshal(source); }