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); } }
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);
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);
private void reportXml(final Request request, final Response response, final String report, final String message) { response.setContentType(MediaType.APPLICATION_XML); try { final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); final Element rootElement = document.createElement("error"); document.appendChild(rootElement); if (report != null && report.length() > 0) { final Element error = document.createElement("error"); final Text text = document.createTextNode(report); error.appendChild(text); rootElement.appendChild(error); } if (message != null && message.length() > 0) { final Element error = document.createElement("error_description"); final Text text = document.createTextNode(message); error.appendChild(text); rootElement.appendChild(error); } DOMImplementationLS domImplementation = (DOMImplementationLS) document.getImplementation(); LSSerializer lsSerializer = domImplementation.createLSSerializer(); response.getReporter().print(lsSerializer.writeToString(document)); } catch (ParserConfigurationException | IOException e) { LOGGER.warning(ValveCodes.ERROR_REPORT, "An error occurred while generating XML response for error.", e); } }
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);
DocumentBuilder b = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = b.parse(...); // Parent of existing Block elements and new Address elemet // Might be retrieved differently depending on // actual structure Element parent = document.getDocumentElement(); Element address = document.createElement("address"); NodeList nl = parent.getElementsByTagName("Block"); for (int i = 0; i < nl.getLength(); ++i) { Element block = (Element) nl.item(i); if (i == 0) parent.insertBefore(address, block); parent.removeChild(block); address.appendChild(block); } // UPDATE: how to pretty print LSSerializer serializer = ((DOMImplementationLS)document.getImplementation()).createLSSerializer(); serializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); LSOutput output = ((DOMImplementationLS)document.getImplementation()).createLSOutput(); output.setByteStream(System.out); serializer.write(document, output);
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)); for (int i = 0; i < iMax; i++) { final Node item = footnotes.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);
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setNamespaceAware(true); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(new File("doc1.xml")); Element content = (Element)doc.getElementsByTagNameNS("http://comResponse.engine/response", "content").item(0); if (content != null) { System.out.println(content.getTextContent()); LSSerializer ser = ((DOMImplementationLS)doc.getImplementation()).createLSSerializer(); if (content.getFirstChild() != null) { System.out.println(ser.writeToString(content.getFirstChild())); } }
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 );
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()); } } }
DocumentBuilder docBuilder = dbFactory.newDocumentBuilder(); docBuilder.setEntityResolver(Utils.getComponent(EntityResolver.class)); String tidied = tidyOutput.toString().trim(); if (StringUtils.isEmpty(tidied)) { tidied = input.trim(); Document doc = docBuilder.parse(new InputSource(new StringReader(tidied))); List<String> seenIDs = new ArrayList<String>(); this.cleanIDs(doc.getDocumentElement(), seenIDs); LSOutput output = lsImpl.createLSOutput(); StringWriter result = new StringWriter(); output.setCharacterStream(result); LSSerializer serializer = lsImpl.createLSSerializer(); serializer.setNewLine("\n"); output.setEncoding(doc.getXmlEncoding()); serializer.write(doc, output); return result.toString(); } catch (Exception ex) {
@Test public void testXMLDocsAsSearchOptions() throws ParserConfigurationException, SAXException, IOException, ResourceNotFoundException, ForbiddenUserException, FailedRequestException, ResourceNotResendableException { String optionsName = "invalid"; Document domDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element root = domDocument.createElementNS("http://marklogic.com/appservices/search","options"); Element rf = domDocument.createElementNS("http://marklogic.com/appservices/search","return-facets"); rf.setTextContent("true"); root.appendChild(rf); root.setAttributeNS("http://www.w3.org/XML/1998/namespace", "lang", "en"); // MarkLogic adds this if I don't domDocument.appendChild(root); QueryOptionsManager queryOptionsMgr = Common.adminClient.newServerConfigManager().newQueryOptionsManager(); queryOptionsMgr.writeOptions(optionsName, new DOMHandle(domDocument)); String domString = ((DOMImplementationLS) DocumentBuilderFactory.newInstance().newDocumentBuilder() .getDOMImplementation()).createLSSerializer().writeToString(domDocument); String optionsString = queryOptionsMgr.readOptions(optionsName, new StringHandle()).get(); assertNotNull("Read null string for XML content",optionsString); logger.debug("Two XML Strings {} and {}", domString, optionsString); Document readDoc = queryOptionsMgr.readOptions(optionsName, new DOMHandle()).get(); assertNotNull("Read null document for XML content",readDoc); }
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(); } }