下面列出了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);
}
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();
}
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);
}
}
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;
}
}
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);
}
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);
}
}
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.*\\?>", "");
}
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);
}
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);
}
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);
}
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;
}
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);
}
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);
}
@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: ");
}
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;
}
public static String getStringFromDoc(Document doc) {
DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
LSSerializer lsSerializer = domImplementation.createLSSerializer();
return lsSerializer.writeToString(doc);
}
/**
* 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);
}
/**
* 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);
}
/**
* 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);
}
/**
* 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);
}