final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement(); final Boolean keepDeclaration = Boolean.valueOf(xml.startsWith("<?xml")); final LSSerializer writer = impl.createLSSerializer(); writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); // Set this to true if the output needs to be beautified. writer.getDomConfig().setParameter("xml-declaration", keepDeclaration); // Set this to true if the declaration is needed to be outputted. return writer.writeToString(document); } catch (Exception e) { throw new RuntimeException(e);
public static String getIndented(String inXml) throws IOException { try { final InputSource src = new InputSource(new StringReader(inXml)); final Document domDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src); String encoding = domDoc.getXmlEncoding(); if (encoding == null) { // defaults to UTF-8 encoding = "UTF-8"; } final Node document = domDoc.getDocumentElement(); final boolean keepDeclaration = inXml.startsWith("<?xml"); final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); final LSSerializer writer = impl.createLSSerializer(); writer.setNewLine("\n"); writer.getDomConfig().setParameter("format-pretty-print", true); // Set this to true if the output needs to be beautified. writer.getDomConfig().setParameter("xml-declaration", keepDeclaration); // Set this to true if the declaration is needed to be outputted. LSOutput lsOutput = impl.createLSOutput(); lsOutput.setEncoding(encoding); Writer stringWriter = new StringWriter(); lsOutput.setCharacterStream(stringWriter); writer.write(document, lsOutput); return stringWriter.toString(); } catch (ParserConfigurationException | SAXException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) { throw new XMLException(null, ex); } }
private Document getDocument(InputStream is) throws InstantiationException, IllegalAccessException, ClassNotFoundException { DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS impl = (DOMImplementationLS)registry.getDOMImplementation("LS"); LSParser parser = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); // we need to ignore whitespace here so the nodeToString() method will be able to indent it properly: parser.setFilter(new IgnoreWhitespaceFilter()); LSInput domInput = impl.createLSInput(); domInput.setByteStream(is); return parser.parse(domInput); }
private static String prettyFormat(Document document, boolean keepXmlDeclaration) { try { DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS domImplementation = (DOMImplementationLS) registry.getDOMImplementation("LS"); Writer stringWriter = new StringWriter(); LSOutput formattedOutput = domImplementation.createLSOutput(); formattedOutput.setCharacterStream(stringWriter); LSSerializer domSerializer = domImplementation.createLSSerializer(); domSerializer.getDomConfig().setParameter("format-pretty-print", true); // Set this to true if the declaration is needed to be in the output. domSerializer.getDomConfig().setParameter("xml-declaration", keepXmlDeclaration); domSerializer.write(document, formattedOutput); return stringWriter.toString(); } catch (Exception e) { throw new RuntimeException(FORMAT_ERROR, e); } }
private static String prettyPrintXmlDocument(Document document) { // Pretty-prints a DOM document to XML using DOM Load and Save's LSSerializer. // Note that the "format-pretty-print" DOM configuration parameter can only be set in JDK 1.6+. DOMImplementation domImplementation = document.getImplementation(); if (domImplementation.hasFeature("LS", "3.0") && domImplementation.hasFeature("Core", "2.0")) { DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementation.getFeature("LS", "3.0"); LSSerializer lsSerializer = domImplementationLS.createLSSerializer(); DOMConfiguration domConfiguration = lsSerializer.getDomConfig(); if (domConfiguration.canSetParameter("format-pretty-print", Boolean.TRUE)) { lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); LSOutput lsOutput = domImplementationLS.createLSOutput(); lsOutput.setEncoding("UTF-8"); StringWriter stringWriter = new StringWriter(); lsOutput.setCharacterStream(stringWriter); lsSerializer.write(document, lsOutput); return stringWriter.toString(); } else { throw new RuntimeException("DOMConfiguration 'format-pretty-print' parameter isn't settable."); } } else { throw new RuntimeException("DOM 3.0 LS and/or DOM 2.0 Core not supported."); } }
.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); DOMImplementation domImpl = db.getDOMImplementation(); Document document = buildExampleDocumentWithNamespaces(domImpl); serialize(domImpl, document); Document document = domImpl.createDocument("urn:example.namespace", "my:example", null); Element element = document.createElementNS("http://another.namespace", "element"); document.getDocumentElement().appendChild(element); return document; LSSerializer lss = ls.createLSSerializer(); LSOutput lso = ls.createLSOutput(); lso.setByteStream(System.out); lss.write(document, lso);
String path = "src/a/testConfig.xml"; try { Document xmlDocument = DocumentBuilderFactory.newInstance() .newDocumentBuilder().parse(path); evaluate(xmlDocument, XPathConstants.NODESET); Document newXmlDocument = DocumentBuilderFactory.newInstance() .newDocumentBuilder().newDocument(); Element root = newXmlDocument.createElement("root"); newXmlDocument.appendChild(root); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); Node copyNode = newXmlDocument.importNode(node, true); root.appendChild(copyNode); (DOMImplementationLS) document.getImplementation(); LSSerializer lsSerializer = domImplementationLS.createLSSerializer(); String string = lsSerializer.writeToString(document); System.out.println(string);
Document xmldoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element element = xmldoc.createElement("TestElement"); xmldoc.appendChild(element); element.appendChild(xmldoc.createCDATASection("first line\nsecond line\n")); (DOMImplementationLS)registry.getDOMImplementation("LS"); LSSerializer writer = impl.createLSSerializer(); String str = writer.writeToString(xmldoc); Document xmldoc2 = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input); Node vs = xmldoc2.getElementsByTagName("TestElement").item(0);
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setValidating(false); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(new InputSource(new StringReader(XML))); NodeList childNodes = document.getDocumentElement().getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { System.out.println(childNodes.item(i)); final LSSerializer writer = impl.createLSSerializer(); writer.getDomConfig().setParameter("xml-declaration", false); writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); System.out.println(writer.writeToString(document));
public static String formatDocumentBody(String xml) { try { final InputSource src = new InputSource(new StringReader(xml)); final DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(false); final Document document = builderFactory.newDocumentBuilder().parse(src); final NodeList bodies = document.getElementsByTagName("w:body"); final NodeList sections = document.getElementsByTagName("w:sectPr"); final NodeList footnotes = document.getElementsByTagName("w:footnote"); final Boolean keepDeclaration = Boolean.valueOf(xml.startsWith("<?xml")); final LSSerializer writer = impl.createLSSerializer(); writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); // Set this to true if the output needs to be beautified. writer.getDomConfig().setParameter("xml-declaration", false); for (int i = 0; i < iMax; i++) { final Node item = bodies.item(i); sb.append(writer.writeToString(item));
public static String readXmlAndResolveReferences(BufferedReader reader) { Document document; try { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); DocumentBuilder domBuilder = domFactory.newDocumentBuilder(); domBuilder.setErrorHandler(new SimpleErrorHandler()); document = domBuilder.parse(new InputSource(reader)); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } catch (SAXException e) { throw new RuntimeException(e); } DOMImplementationLS domImplementation = (DOMImplementationLS) document.getImplementation(); LSSerializer lsSerializer = domImplementation.createLSSerializer(); LSOutput out = domImplementation.createLSOutput(); StringWriter sw = new StringWriter(); out.setCharacterStream(sw); out.setEncoding("UTF-8"); lsSerializer.write(document, out); return sw.toString(); }
public static String sortDocumentParts(String xml) { try { final InputSource src = new InputSource(new StringReader(xml)); final DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(false); final Document document = builderFactory.newDocumentBuilder().parse(src); final LSSerializer writer = impl.createLSSerializer(); writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); // Set this to true if the output needs to be beautified. writer.getDomConfig().setParameter("xml-declaration", false);
public static void writeDoc() throws Exception { Document domDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element root = domDocument.createElement("root"); root.setAttribute("xml:lang", "en"); root.setAttribute("foo", "bar"); root.appendChild(domDocument.createElement("child")); root.appendChild(domDocument.createTextNode("mixed")); domDocument.appendChild(root); @SuppressWarnings("unused") String domString = ((DOMImplementationLS) DocumentBuilderFactory.newInstance().newDocumentBuilder() .getDOMImplementation()).createLSSerializer().writeToString(domDocument); XMLDocumentManager docMgr = client.newXMLDocumentManager(); docMgr.write(docId, new DOMHandle().with(domDocument)); }
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); String ns1 = "http://example.com/ns1"; String ns2 = "http://example.com/ns2"; Element root = doc.createElementNS(ns1, "pf1:root"); root.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:pf2", ns2); doc.appendChild(root); Element foo = doc.createElementNS(ns1, "pf1:foo"); foo.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:pf1", ns1); foo.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:pf2", ns2); root.appendChild(foo); DOMImplementationLS domImp = (DOMImplementationLS)doc.getImplementation(); LSSerializer ser = domImp.createLSSerializer(); System.out.println(ser.writeToString(doc));
InputStream parsingStream = new FileInputStream(file) DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); builder.setEntityResolver(new Resolver()); Document doc = builder.parse( parsingStream ); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); DOMImplementationLS domImplementationLS = (DOMImplementationLS)doc.getImplementation().getFeature( "LS", "3.0" ); LSOutput lsOutput = domImplementationLS.createLSOutput(); lsOutput.setByteStream( outputStream ); LSSerializer lsSerializer = domImplementationLS.createLSSerializer(); lsSerializer.write( doc, lsOutput ); byte[] byteArray = outputStream.toByteArray(); ByteArrayInputStream importStream = new ByteArrayInputStream( byteArray ); Preferences.importPreferences( importStream );
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = factory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element root = doc.createElement("root"); root.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:noNamespaceSchemaLocation", "my.xsd"); root.appendChild(doc.createElement("foo")); doc.appendChild(root); // see result DOMImplementationLS dls = (DOMImplementationLS) doc.getImplementation(); System.out.println(dls.createLSSerializer().writeToString(doc));
// output stream ByteArrayOutputStream buffer = new ByteArrayOutputStream(); // create XML DOM InputSource src = new InputSource(new StringReader("<x>pi: \u03A0</x>")); Document doc = DocumentBuilderFactory.newInstance() .newDocumentBuilder() .parse(src); // serialize DOMImplementationLS impl = (DOMImplementationLS) doc.getImplementation(); LSOutput out = impl.createLSOutput(); out.setEncoding("ISO-8859-1"); out.setByteStream(buffer); impl.createLSSerializer().write(doc, out); // proof String decoded = new String(buffer.toByteArray(), Charset.forName("ISO-8859-1")); System.out.println(decoded);
protected void printResponse() { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); DOMImplementationLS ls = (DOMImplementationLS)docBuilder.getDOMImplementation(); LSSerializer lss = ls.createLSSerializer(); System.out.println(lss.writeToString(_docResponse)); } catch (ParserConfigurationException e) { s_logger.error("Error parsing the repsonse : " + e.toString()); } } }
import java.io.StringWriter; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.ls.*; public class DomIO { public static void main(String[] args) throws Exception { Document doc = DocumentBuilderFactory.newInstance() .newDocumentBuilder() .newDocument(); doc.appendChild(doc.createElement("foo")); System.out.println(getDocumentString(doc)); } public static String getDocumentString(Document doc) { DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation(); LSSerializer lsSerializer = domImplementation.createLSSerializer(); LSOutput lsOut = domImplementation.createLSOutput(); lsOut.setEncoding("UTF-8"); lsOut.setCharacterStream(new StringWriter()); lsSerializer.write(doc, lsOut); return lsOut.getCharacterStream().toString(); } }
/** Invoke code that may trigger leak */ public static void triggerLeak() throws ParserConfigurationException { // Alternative 1 DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument().normalizeDocument(); // Alternative 2 Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); DOMImplementationLS implementation = (DOMImplementationLS)document.getImplementation(); implementation.createLSSerializer().writeToString(document); } }