Java Code Examples for org.w3c.dom.ls.LSSerializer#writeToString()

The following examples show how to use org.w3c.dom.ls.LSSerializer#writeToString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PersistentResourceXMLParserTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static String normalizeXML(String xml) throws Exception {
    // Remove all white space adjoining tags ("trim all elements")
    xml = xml.replaceAll("\\s*<", "<");
    xml = xml.replaceAll(">\\s*", ">");

    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    DOMImplementationLS domLS = (DOMImplementationLS) registry.getDOMImplementation("LS");
    LSParser lsParser = domLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);

    LSInput input = domLS.createLSInput();
    input.setStringData(xml);
    Document document = lsParser.parse(input);

    LSSerializer lsSerializer = domLS.createLSSerializer();
    lsSerializer.getDomConfig().setParameter("comments", Boolean.FALSE);
    lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
    return lsSerializer.writeToString(document);
}
 
Example 2
Source File: ConfigPersister.java    From jmkvpropedit with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void load(File f) throws ConfigPersisterException {
    try {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.parse(f);

		DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
	    LSSerializer lsSerializer = domImplementation.createLSSerializer();
	    String configString = lsSerializer.writeToString(doc);

    	_config = (Config) _xstream.fromXML(convertToCurrent(configString));
    	setConfigPath(f);
	} catch (Exception e) {
		throw new ConfigPersisterException(e);
	}
}
 
Example 3
Source File: XmlUtils.java    From Doradus with Apache License 2.0 6 votes vote down vote up
static public String getInnerXmlText(Node xmlNode)
{
    StringBuilder result = new StringBuilder();

    Document xmlDocument = xmlNode.getOwnerDocument();
    DOMImplementation xmlDocumentImpl = xmlDocument.getImplementation();
    DOMImplementationLS lsImpl = (DOMImplementationLS) xmlDocumentImpl.getFeature("LS", "3.0");
    LSSerializer lsSerializer = lsImpl.createLSSerializer();

    NodeList childNodes = xmlNode.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        String childText = lsSerializer.writeToString(childNodes.item(i));
        int pos = childText.indexOf("?>");
        if (pos > -1) {
            childText = childText.substring(pos + 2);
        }
        result.append(childText);
    }

    return result.toString();
}
 
Example 4
Source File: ConfigPersister.java    From PyramidShader with GNU General Public License v3.0 6 votes vote down vote up
public void load(File f) throws ConfigPersisterException {
    try {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.parse(f);

		DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
	    LSSerializer lsSerializer = domImplementation.createLSSerializer();
	    String configString = lsSerializer.writeToString(doc);

    	_config = (Config) _xstream.fromXML(convertToCurrent(configString));
    	setConfigPath(f);
	} catch (Exception e) {
		throw new ConfigPersisterException(e);
	}
}
 
Example 5
Source File: AbstractMethodErrorTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.newDocument();

    DOMImplementation impl = document.getImplementation();
    DOMImplementationLS implLS = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer dsi = implLS.createLSSerializer();

    /* We should have here incorrect document without getXmlVersion() method:
     * Such Document is generated by replacing the JDK bootclasses with it's
     * own Node,Document and DocumentImpl classes (see run.sh). According to
     * XERCESJ-1007 the AbstractMethodError should be thrown in such case.
     */
    String result = dsi.writeToString(document);
    System.out.println("Result:" + result);
}
 
Example 6
Source File: Utils.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static String format(String xml) {

        try {
            final InputSource src = new InputSource(new StringReader(xml));
            final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
            final Boolean keepDeclaration = Boolean.valueOf(xml.startsWith("<?xml"));

            //May need this: System.setProperty(DOMImplementationRegistry.PROPERTY,"com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl");


            final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
            final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
            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) {
            return xml;
        }
    }
 
Example 7
Source File: HttpParserTest.java    From teamengine with Apache License 2.0 5 votes vote down vote up
static String writeNodeToString(Node node) throws ClassNotFoundException,
        InstantiationException, IllegalAccessException, ClassCastException {
    DOMImplementationRegistry registry = DOMImplementationRegistry
            .newInstance();
    DOMImplementationLS impl = (DOMImplementationLS) registry
            .getDOMImplementation("LS");
    LSSerializer serializer = impl.createLSSerializer();
    return serializer.writeToString(node);
}
 
Example 8
Source File: SymbolExplorerTreeCreator.java    From mil-sym-java with Apache License 2.0 5 votes vote down vote up
public String buildXMLString(int symStd)
{
    Document xml = buildXML(symStd);
    DOMImplementationLS domImplLS = (DOMImplementationLS)xml.getImplementation();
    LSSerializer serializer = domImplLS.createLSSerializer();
    String strXML = serializer.writeToString(xml);
    return strXML;
}
 
Example 9
Source File: Bug6354955.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private String getOuterXML(Node node) {
    DOMImplementationLS domImplementation = (DOMImplementationLS) node.getOwnerDocument().getImplementation();
    LSSerializer lsSerializer = domImplementation.createLSSerializer();
    if (!(node instanceof Document)) {
        lsSerializer.getDomConfig().setParameter("xml-declaration", false);
    }
    return lsSerializer.writeToString(node);
}
 
Example 10
Source File: Util.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static String format(Element data) {
    LSSerializer ser = ((DOMImplementationLS) data.getOwnerDocument().getImplementation().getFeature("LS", "3.0")).createLSSerializer();
    try {
        ser.getDomConfig().setParameter("format-pretty-print", true);
        ser.getDomConfig().setParameter("xml-declaration", false);
    } catch (DOMException ignore) {}
    return ser.writeToString(data);
}
 
Example 11
Source File: FreeWorshipParser.java    From Quelea with GNU General Public License v3.0 5 votes vote down vote up
private String innerXml(Node node) {
    DOMImplementationLS lsImpl = (DOMImplementationLS) node.getOwnerDocument().getImplementation().getFeature("LS", "3.0");
    LSSerializer lsSerializer = lsImpl.createLSSerializer();
    NodeList childNodes = node.getChildNodes();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < childNodes.getLength(); i++) {
        String str = lsSerializer.writeToString(childNodes.item(i));
        if (str.endsWith("<br/>")) {
            str = "\n";
        }
        sb.append(str);
    }
    return sb.toString().replaceAll("<\\?xml.*\\?>", "");
}
 
Example 12
Source File: HtmlAssetTranslator.java    From RipplePower with Apache License 2.0 4 votes vote down vote up
private static void translateOneFile(String language, Path targetHtmlDir, Path sourceFile,
		String translationTextTranslated) throws IOException {

	Path destFile = targetHtmlDir.resolve(sourceFile.getFileName());

	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	Document document;
	try {
		DocumentBuilder builder = factory.newDocumentBuilder();
		document = builder.parse(sourceFile.toFile());
	} catch (ParserConfigurationException pce) {
		throw new IllegalStateException(pce);
	} catch (SAXException sae) {
		throw new IOException(sae);
	}

	Element rootElement = document.getDocumentElement();
	rootElement.normalize();

	Queue<Node> nodes = new LinkedList<>();
	nodes.add(rootElement);

	while (!nodes.isEmpty()) {
		Node node = nodes.poll();
		if (shouldTranslate(node)) {
			NodeList children = node.getChildNodes();
			for (int i = 0; i < children.getLength(); i++) {
				nodes.add(children.item(i));
			}
		}
		if (node.getNodeType() == Node.TEXT_NODE) {
			String text = node.getTextContent();
			if (!text.trim().isEmpty()) {
				text = StringsResourceTranslator.translateString(text, language);
				node.setTextContent(' ' + text + ' ');
			}
		}
	}

	Node translateText = document.createTextNode(translationTextTranslated);
	Node paragraph = document.createElement("p");
	paragraph.appendChild(translateText);
	Node body = rootElement.getElementsByTagName("body").item(0);
	body.appendChild(paragraph);

	DOMImplementationRegistry registry;
	try {
		registry = DOMImplementationRegistry.newInstance();
	} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
		throw new IllegalStateException(e);
	}

	DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
	LSSerializer writer = impl.createLSSerializer();
	String fileAsString = writer.writeToString(document);
	// Replace default XML header with HTML DOCTYPE
	fileAsString = fileAsString.replaceAll("<\\?xml[^>]+>", "<!DOCTYPE HTML>");
	Files.write(destFile, Collections.singleton(fileAsString), StandardCharsets.UTF_8);
}
 
Example 13
Source File: LSSerializerTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testXML11() {

    /**
     * XML 1.1 document to parse.
     */
    final String XML11_DOCUMENT = "<?xml version=\"1.1\" encoding=\"UTF-16\"?>\n" + "<hello>" + "world" + "<child><children/><children/></child>"
            + "</hello>";

    /**JDK-8035467
     * no newline in default output
     */
    final String XML11_DOCUMENT_OUTPUT =
            "<?xml version=\"1.1\" encoding=\"UTF-16\"?>"
            + "<hello>"
            + "world"
            + "<child><children/><children/></child>"
            + "</hello>";

    // it all begins with a Document
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = null;
    try {
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException parserConfigurationException) {
        parserConfigurationException.printStackTrace();
        Assert.fail(parserConfigurationException.toString());
    }
    Document document = null;

    StringReader stringReader = new StringReader(XML11_DOCUMENT);
    InputSource inputSource = new InputSource(stringReader);
    try {
        document = documentBuilder.parse(inputSource);
    } catch (SAXException saxException) {
        saxException.printStackTrace();
        Assert.fail(saxException.toString());
    } catch (IOException ioException) {
        ioException.printStackTrace();
        Assert.fail(ioException.toString());
    }

    // query DOM Interfaces to get to a LSSerializer
    DOMImplementation domImplementation = documentBuilder.getDOMImplementation();
    DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementation;
    LSSerializer lsSerializer = domImplementationLS.createLSSerializer();

    System.out.println("Serializer is: " + lsSerializer.getClass().getName() + " " + lsSerializer);

    // get default serialization
    String defaultSerialization = lsSerializer.writeToString(document);

    System.out.println("XML 1.1 serialization = \"" + defaultSerialization + "\"");

    // output should == input
    Assert.assertEquals(XML11_DOCUMENT_OUTPUT, defaultSerialization, "Invalid serialization of XML 1.1 document: ");
}
 
Example 14
Source File: CombinedQueryBuilderImpl.java    From java-client-api with Apache License 2.0 4 votes vote down vote up
private CombinedQueryDefinitionImpl parseCombinedQuery(RawCombinedQueryDefinition qdef) {
  DOMHandle handle = new DOMHandle();
  HandleAccessor.receiveContent(handle, HandleAccessor.contentAsString(qdef.getHandle()));
  Document combinedQueryXml = handle.get();
  DOMImplementationLS domImplementation = (DOMImplementationLS) combinedQueryXml.getImplementation();
  LSSerializer lsSerializer = domImplementation.createLSSerializer();
  lsSerializer.getDomConfig().setParameter("xml-declaration", false);

  NodeList nl = combinedQueryXml.getElementsByTagNameNS("http://marklogic.com/appservices/search", "options");
  Node n = nl.item(0);
  String options = null;
  StringHandle optionsHandle = null;
  if (n != null) {
    options = lsSerializer.writeToString(n);
    optionsHandle = new StringHandle(options).withFormat(Format.XML);
  }

  //TODO this could be more than one string...
  nl = combinedQueryXml.getElementsByTagNameNS("http://marklogic.com/appservices/search", "qtext");
  n = nl.item(0);
  String qtext = null;
  if (n != null) {
    qtext = lsSerializer.writeToString(n);
  }

  nl = combinedQueryXml.getElementsByTagNameNS("http://marklogic.com/appservices/search", "sparql");
  n = nl.item(0);
  String sparql = null;
  if (n != null) {
    sparql = lsSerializer.writeToString(n);
  }

  nl = combinedQueryXml.getElementsByTagNameNS("http://marklogic.com/appservices/search", "query");
  n = nl.item(0);
  String query = null;
  if (n != null) {
    query = lsSerializer.writeToString(nl.item(0));
  }
  StringHandle structuredQueryHandle = new StringHandle().with(query).withFormat(Format.XML);
  RawStructuredQueryDefinition structuredQueryDefinition =
    new RawQueryDefinitionImpl.Structured(structuredQueryHandle);
  return new CombinedQueryDefinitionImpl(structuredQueryDefinition,
    optionsHandle, qtext, sparql);
}
 
Example 15
Source File: DOML3InputSourceFactoryImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public InputSource newInputSource(String filename) throws Exception {
    // Create DOMImplementationLS, and DOM L3 LSParser
    DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
    DocumentBuilder bldr = fact.newDocumentBuilder();
    DOMImplementationLS impl = (DOMImplementationLS) bldr.getDOMImplementation();
    LSParser domparser = impl.createLSParser(MODE_SYNCHRONOUS, null);
    domparser.setFilter(new MyDOMBuilderFilter());

    // Parse the xml document to create the DOM Document using
    // the DOM L3 LSParser and a LSInput (formerly LSInputSource)
    Document doc = null;
    LSInput src = impl.createLSInput();
    // register the input file with the input source...
    String systemId = filenameToURL(filename);
    src.setSystemId(systemId);
    try (Reader reader = new FileReader(filename)) {
        src.setCharacterStream(reader);
        src.setEncoding("UTF-8");
        doc = domparser.parse(src);
    }

    // Use DOM L3 LSSerializer (previously called a DOMWriter)
    // to serialize the xml doc DOM to a file stream.
    String tmpCatalog = Files.createTempFile(Paths.get(USER_DIR), "catalog.xml", null).toString();

    LSSerializer domserializer = impl.createLSSerializer();
    domserializer.setFilter(new MyDOMWriterFilter());
    domserializer.getNewLine();
    DOMConfiguration config = domserializer.getDomConfig();
    config.setParameter("xml-declaration", Boolean.TRUE);
    String result = domserializer.writeToString(doc);
    try (FileWriter os = new FileWriter(tmpCatalog, false)) {
        os.write(result);
        os.flush();
    }

    // Return the Input Source created from the Serialized DOM L3 Document.
    InputSource catsrc = new InputSource(new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(tmpCatalog)))));
    catsrc.setSystemId(systemId);
    return catsrc;
}
 
Example 16
Source File: ReportExport.java    From zap-extensions with Apache License 2.0 4 votes vote down vote up
public static String getStringFromDoc(Document doc) {
    DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
    LSSerializer lsSerializer = domImplementation.createLSSerializer();
    return lsSerializer.writeToString(doc);
}
 
Example 17
Source File: CoreDocumentImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 3 votes vote down vote up
/**
 * DOM Level 3 WD - Experimental.
 * Save the document or the given node and all its descendants to a string
 * (i.e. serialize the document or node).
 * <br>The parameters used in the <code>LSSerializer</code> interface are
 * assumed to have their default values when invoking this method.
 * <br> The result of a call to this method is the same the result of a
 * call to <code>LSSerializer.writeToString</code> with the document as
 * the node to write.
 * @param node Specifies what to serialize, if this parameter is
 *   <code>null</code> the whole document is serialized, if it's
 *   non-null the given node is serialized.
 * @return The serialized document or <code>null</code> in case an error
 *   occurred.
 * @exception DOMException
 *   WRONG_DOCUMENT_ERR: Raised if the node passed in as the node
 *   parameter is from an other document.
 */
public String saveXML(Node node)
        throws DOMException {
    if (errorChecking && node != null
            && this != node.getOwnerDocument()) {
        String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "WRONG_DOCUMENT_ERR", null);
        throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, msg);
    }
    DOMImplementationLS domImplLS = (DOMImplementationLS) DOMImplementationImpl.getDOMImplementation();
    LSSerializer xmlWriter = domImplLS.createLSSerializer();
    if (node == null) {
        node = this;
    }
    return xmlWriter.writeToString(node);
}
 
Example 18
Source File: CoreDocumentImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * DOM Level 3 WD - Experimental.
 * Save the document or the given node and all its descendants to a string
 * (i.e. serialize the document or node).
 * <br>The parameters used in the <code>LSSerializer</code> interface are
 * assumed to have their default values when invoking this method.
 * <br> The result of a call to this method is the same the result of a
 * call to <code>LSSerializer.writeToString</code> with the document as
 * the node to write.
 * @param node Specifies what to serialize, if this parameter is
 *   <code>null</code> the whole document is serialized, if it's
 *   non-null the given node is serialized.
 * @return The serialized document or <code>null</code> in case an error
 *   occurred.
 * @exception DOMException
 *   WRONG_DOCUMENT_ERR: Raised if the node passed in as the node
 *   parameter is from an other document.
 */
public String saveXML(Node node)
        throws DOMException {
    if (errorChecking && node != null
            && this != node.getOwnerDocument()) {
        String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "WRONG_DOCUMENT_ERR", null);
        throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, msg);
    }
    DOMImplementationLS domImplLS = (DOMImplementationLS) DOMImplementationImpl.getDOMImplementation();
    LSSerializer xmlWriter = domImplLS.createLSSerializer();
    if (node == null) {
        node = this;
    }
    return xmlWriter.writeToString(node);
}
 
Example 19
Source File: CoreDocumentImpl.java    From jdk1.8-source-analysis with Apache License 2.0 3 votes vote down vote up
/**
 * DOM Level 3 WD - Experimental.
 * Save the document or the given node and all its descendants to a string
 * (i.e. serialize the document or node).
 * <br>The parameters used in the <code>LSSerializer</code> interface are
 * assumed to have their default values when invoking this method.
 * <br> The result of a call to this method is the same the result of a
 * call to <code>LSSerializer.writeToString</code> with the document as
 * the node to write.
 * @param node Specifies what to serialize, if this parameter is
 *   <code>null</code> the whole document is serialized, if it's
 *   non-null the given node is serialized.
 * @return The serialized document or <code>null</code> in case an error
 *   occurred.
 * @exception DOMException
 *   WRONG_DOCUMENT_ERR: Raised if the node passed in as the node
 *   parameter is from an other document.
 */
public String saveXML(Node node)
        throws DOMException {
    if (errorChecking && node != null
            && this != node.getOwnerDocument()) {
        String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "WRONG_DOCUMENT_ERR", null);
        throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, msg);
    }
    DOMImplementationLS domImplLS = (DOMImplementationLS) DOMImplementationImpl.getDOMImplementation();
    LSSerializer xmlWriter = domImplLS.createLSSerializer();
    if (node == null) {
        node = this;
    }
    return xmlWriter.writeToString(node);
}
 
Example 20
Source File: CoreDocumentImpl.java    From hottub with GNU General Public License v2.0 3 votes vote down vote up
/**
 * DOM Level 3 WD - Experimental.
 * Save the document or the given node and all its descendants to a string
 * (i.e. serialize the document or node).
 * <br>The parameters used in the <code>LSSerializer</code> interface are
 * assumed to have their default values when invoking this method.
 * <br> The result of a call to this method is the same the result of a
 * call to <code>LSSerializer.writeToString</code> with the document as
 * the node to write.
 * @param node Specifies what to serialize, if this parameter is
 *   <code>null</code> the whole document is serialized, if it's
 *   non-null the given node is serialized.
 * @return The serialized document or <code>null</code> in case an error
 *   occurred.
 * @exception DOMException
 *   WRONG_DOCUMENT_ERR: Raised if the node passed in as the node
 *   parameter is from an other document.
 */
public String saveXML(Node node)
        throws DOMException {
    if (errorChecking && node != null
            && this != node.getOwnerDocument()) {
        String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "WRONG_DOCUMENT_ERR", null);
        throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, msg);
    }
    DOMImplementationLS domImplLS = (DOMImplementationLS) DOMImplementationImpl.getDOMImplementation();
    LSSerializer xmlWriter = domImplLS.createLSSerializer();
    if (node == null) {
        node = this;
    }
    return xmlWriter.writeToString(node);
}