org.w3c.dom.ls.LSSerializer#writeToString ( )源码实例Demo

下面列出了org.w3c.dom.ls.LSSerializer#writeToString ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

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);
}
 
源代码2 项目: Doradus   文件: XmlUtils.java
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();
}
 
源代码3 项目: PyramidShader   文件: ConfigPersister.java
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);
	}
}
 
源代码4 项目: SI   文件: Utils.java
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;
        }
    }
 
源代码5 项目: openjdk-jdk9   文件: AbstractMethodErrorTest.java
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);
}
 
源代码6 项目: jmkvpropedit   文件: ConfigPersister.java
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);
	}
}
 
源代码7 项目: Quelea   文件: FreeWorshipParser.java
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.*\\?>", "");
}
 
源代码8 项目: netbeans   文件: Util.java
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);
}
 
源代码9 项目: teamengine   文件: HttpParserTest.java
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);
}
 
源代码10 项目: openjdk-jdk9   文件: Bug6354955.java
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);
}
 
源代码11 项目: mil-sym-java   文件: SymbolExplorerTreeCreator.java
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;
}
 
源代码12 项目: RipplePower   文件: HtmlAssetTranslator.java
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);
}
 
源代码13 项目: java-client-api   文件: CombinedQueryBuilderImpl.java
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);
}
 
源代码14 项目: openjdk-jdk9   文件: LSSerializerTest.java
@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: ");
}
 
源代码15 项目: openjdk-jdk9   文件: DOML3InputSourceFactoryImpl.java
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;
}
 
源代码16 项目: zap-extensions   文件: ReportExport.java
public static String getStringFromDoc(Document doc) {
    DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
    LSSerializer lsSerializer = domImplementation.createLSSerializer();
    return lsSerializer.writeToString(doc);
}
 
源代码17 项目: jdk1.8-source-analysis   文件: CoreDocumentImpl.java
/**
 * 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);
}
 
源代码18 项目: openjdk-jdk8u   文件: CoreDocumentImpl.java
/**
 * 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);
}
 
源代码19 项目: openjdk-jdk9   文件: CoreDocumentImpl.java
/**
 * 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);
}
 
源代码20 项目: hottub   文件: CoreDocumentImpl.java
/**
 * 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);
}