下面列出了怎么用org.w3c.dom.ls.LSOutput的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Serialize XML objects
*
* @param xmlObject : XACML or SAML objects to be serialized
* @return serialized XACML or SAML objects
*/
private String marshall(XMLObject xmlObject) throws EntitlementProxyException {
try {
doBootstrap();
System.setProperty(DOCUMENT_BUILDER_FACTORY, DOCUMENT_BUILDER_FACTORY_IMPL);
MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
Element element = marshaller.marshall(xmlObject);
ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream();
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
LSOutput output = impl.createLSOutput();
output.setByteStream(byteArrayOutputStrm);
writer.write(element, output);
return new String(byteArrayOutputStrm.toByteArray(), Charset.forName("UTF-8"));
} catch (Exception e) {
log.error("Error Serializing the SAML Response");
throw new EntitlementProxyException("Error Serializing the SAML Response", e);
}
}
/**
* `
* Serialize XML objects
*
* @param xmlObject : XACML or SAML objects to be serialized
* @return serialized XACML or SAML objects
* @throws EntitlementException
*/
private String marshall(XMLObject xmlObject) throws EntitlementException {
try {
doBootstrap();
System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
"org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
MarshallerFactory marshallerFactory = XMLObjectProviderRegistrySupport.getMarshallerFactory();
Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
Element element = marshaller.marshall(xmlObject);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl =
(DOMImplementationLS) registry.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
LSOutput output = impl.createLSOutput();
output.setByteStream(byteArrayOutputStream);
writer.write(element, output);
return byteArrayOutputStream.toString();
} catch (Exception e) {
log.error("Error Serializing the SAML Response");
throw new EntitlementException("Error Serializing the SAML Response", e);
}
}
public static String toXml(Document domDoc) throws TransformerException {
DOMImplementation domImplementation = domDoc.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("xml-declaration", Boolean.TRUE))
lsSerializer.getDomConfig().setParameter("xml-declaration", Boolean.FALSE);
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(domDoc, lsOutput);
return stringWriter.toString();
}
}
return toXml((Node) domDoc);
}
private void format(Document document, Writer writer) {
DOMImplementation implementation = document.getImplementation();
if(implementation.hasFeature(LS_FEATURE_KEY, LS_FEATURE_VERSION) && implementation.hasFeature(CORE_FEATURE_KEY, CORE_FEATURE_VERSION)) {
DOMImplementationLS implementationLS = (DOMImplementationLS) implementation.getFeature(LS_FEATURE_KEY, LS_FEATURE_VERSION);
LSSerializer serializer = implementationLS.createLSSerializer();
DOMConfiguration configuration = serializer.getDomConfig();
configuration.setParameter("format-pretty-print", Boolean.TRUE);
configuration.setParameter("comments", preserveComments);
LSOutput output = implementationLS.createLSOutput();
output.setEncoding("UTF-8");
output.setCharacterStream(writer);
serializer.write(document, output);
}
}
/**
* `
* Serialize XML objects
*
* @param xmlObject : XACML or SAML objects to be serialized
* @return serialized XACML or SAML objects
* @throws EntitlementException
*/
private String marshall(XMLObject xmlObject) throws EntitlementException {
try {
doBootstrap();
System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
"org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
Element element = marshaller.marshall(xmlObject);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl =
(DOMImplementationLS) registry.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
LSOutput output = impl.createLSOutput();
output.setByteStream(byteArrayOutputStream);
writer.write(element, output);
return byteArrayOutputStream.toString();
} catch (Exception e) {
log.error("Error Serializing the SAML Response");
throw new EntitlementException("Error Serializing the SAML Response", e);
}
}
/**
* Serializing a SAML2 object into a String
*
* @param xmlObject object that needs to serialized.
* @return serialized object
* @throws SAMLSSOException
*/
public static String marshall(XMLObject xmlObject) throws SAMLSSOException {
try {
System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
"org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration
.getMarshallerFactory();
Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
Element element = marshaller.marshall(xmlObject);
ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream();
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
LSOutput output = impl.createLSOutput();
output.setByteStream(byteArrayOutputStrm);
writer.write(element, output);
return byteArrayOutputStrm.toString();
} catch (Exception e) {
log.error("Error Serializing the SAML Response");
throw new SAMLSSOException("Error Serializing the SAML Response", e);
}
}
/**
* Serializing a SAML2 object into a String
*
* @param xmlObject object that needs to serialized.
* @return serialized object
* @throws SAML2SSOUIAuthenticatorException
*/
public static String marshall(XMLObject xmlObject) throws SAML2SSOUIAuthenticatorException {
try {
doBootstrap();
System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
"org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration
.getMarshallerFactory();
Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
Element element = marshaller.marshall(xmlObject);
ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream();
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
LSOutput output = impl.createLSOutput();
output.setByteStream(byteArrayOutputStrm);
writer.write(element, output);
return byteArrayOutputStrm.toString();
} catch (Exception e) {
log.error("Error Serializing the SAML Response");
throw new SAML2SSOUIAuthenticatorException("Error Serializing the SAML Response", e);
}
}
private static String marshall(XMLObject xmlObject) throws org.wso2.carbon.identity.base.IdentityException {
try {
System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
"org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
Element element = marshaller.marshall(xmlObject);
ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream();
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl =
(DOMImplementationLS) registry.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
LSOutput output = impl.createLSOutput();
output.setByteStream(byteArrayOutputStrm);
writer.write(element, output);
return byteArrayOutputStrm.toString("UTF-8");
} catch (Exception e) {
log.error("Error Serializing the SAML Response");
throw IdentityException.error("Error Serializing the SAML Response", e);
}
}
/**
* Serializing a SAML2 object into a String
*
* @param xmlObject object that needs to serialized.
* @return serialized object
* @throws Exception
*/
public static String marshall(XMLObject xmlObject) throws Exception {
try {
doBootstrap();
System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
"org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
MarshallerFactory marshallerFactory = XMLObjectProviderRegistrySupport.getMarshallerFactory();
Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
Element element = marshaller.marshall(xmlObject);
ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream();
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl =
(DOMImplementationLS) registry.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
LSOutput output = impl.createLSOutput();
output.setByteStream(byteArrayOutputStrm);
writer.write(element, output);
return byteArrayOutputStrm.toString();
} catch (Exception e) {
throw new Exception("Error Serializing the SAML Response", e);
}
}
/**
* Serializing a SAML2 object into a String
*
* @param xmlObject object that needs to serialized.
* @return serialized object
* @throws Exception
*/
public static String marshall(XMLObject xmlObject) throws Exception {
try {
doBootstrap();
System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
"org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
Element element = marshaller.marshall(xmlObject);
ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream();
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl =
(DOMImplementationLS) registry.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
LSOutput output = impl.createLSOutput();
output.setByteStream(byteArrayOutputStrm);
writer.write(element, output);
return byteArrayOutputStrm.toString();
} catch (Exception e) {
throw new Exception("Error Serializing the SAML Response", e);
}
}
public static String dom2String2(Document document) {
DOMImplementationRegistry registry;
try {
registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS domImplLS = (DOMImplementationLS)registry.getDOMImplementation("LS");
LSSerializer ser = domImplLS.createLSSerializer(); // Create a serializer for the DOM
LSOutput out = domImplLS.createLSOutput();
StringWriter stringOut = new StringWriter(); // Writer will be a String
out.setCharacterStream(stringOut);
ser.write(document, out); // Serialize the DOM
System.out.println( "STRXML = "
+ stringOut.toString() ); // Spit out the DOM as a String
return stringOut.toString();
} catch (Exception e) {
System.err.println("Cannot create registry: "+e.getMessage());
}
return null;
}
/**
* Serialise the given SVG document.
* @param path The file of the future serialised document.
* @return True: the document has been successfully saved.
*/
public boolean saveSVGDocument(final String path) {
if(path == null) {
return false;
}
boolean ok = true;
try {
final DOMImplementationLS impl = (DOMImplementationLS) DOMImplementationRegistry.newInstance().getDOMImplementation("XML 3.0 LS 3.0"); //NON-NLS
final LSSerializer serializer = impl.createLSSerializer();
serializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); //NON-NLS
serializer.getDomConfig().setParameter("namespaces", Boolean.FALSE); //NON-NLS
final LSOutput output = impl.createLSOutput();
final Charset charset = Charset.defaultCharset();
try(final OutputStreamWriter fw = new OutputStreamWriter(Files.newOutputStream(Path.of(path)), charset.newEncoder())) {
output.setEncoding(charset.name());
output.setCharacterStream(fw);
serializer.write(getDocumentElement(), output);
}
}catch(final ClassNotFoundException | InstantiationException | IllegalAccessException | ClassCastException | IOException ex) {
BadaboomCollector.INSTANCE.add(ex);
ok = false;
}
return ok;
}
/***
* Helper method which converts XML Document into pretty formatted string
*
* @param doc to convert
* @return converted XML as String
*/
public static String documentToString(Document doc) {
String strMsg = "";
try {
DOMImplementation domImpl = doc.getImplementation();
DOMImplementationLS domImplLS = (DOMImplementationLS) domImpl.getFeature("LS", "3.0");
LSSerializer lsSerializer = domImplLS.createLSSerializer();
lsSerializer.getDomConfig().setParameter("format-pretty-print", true);
Writer stringWriter = new StringWriter();
LSOutput lsOutput = domImplLS.createLSOutput();
lsOutput.setEncoding("UTF-8");
lsOutput.setCharacterStream(stringWriter);
lsSerializer.write(doc, lsOutput);
strMsg = stringWriter.toString();
} catch (Exception e) {
logger.warn("Error occurred when converting document to string", e);
}
return strMsg;
}
/**
* Writes a DOM Document to the given OutputStream using the "UTF-8"
* encoding. The XML declaration is omitted.
*
* @param outStream
* The destination OutputStream object.
* @param doc
* A Document node.
*/
void writeDocument(OutputStream outStream, Document doc) {
DOMImplementationRegistry domRegistry = null;
try {
domRegistry = DOMImplementationRegistry.newInstance();
// Fortify Mod: Broaden try block to capture all potential exceptions
// } catch (Exception e) {
// LOGR.warning(e.getMessage());
// }
DOMImplementationLS impl = (DOMImplementationLS) domRegistry
.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
writer.getDomConfig().setParameter("xml-declaration", false);
writer.getDomConfig().setParameter("format-pretty-print", true);
LSOutput output = impl.createLSOutput();
output.setEncoding("UTF-8");
output.setByteStream(outStream);
writer.write(doc, output);
} catch (Exception e) {
LOGR.warning(e.getMessage());
}
}
private static String elementToString(Element e) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DOMImplementationLS ls = (DOMImplementationLS) e.getOwnerDocument().getImplementation().getFeature("LS", "3.0"); // NOI18N
LSOutput output = ls.createLSOutput();
output.setByteStream(baos);
LSSerializer ser = ls.createLSSerializer();
ser.write(e, output);
return baos.toString();
}
private void _dumpDocument( Document doc, String title ) {
if( null == title || title.isEmpty() ) {
title = NbBundle.getMessage(WebBrowserImpl.class, "Lbl_GenericDomDumpTitle");
}
InputOutput io = IOProvider.getDefault().getIO( title, true );
io.select();
try {
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation( "XML 3.0 LS 3.0" ); //NOI18N
if( null == impl ) {
io.getErr().println( NbBundle.getMessage(WebBrowserImpl.class, "Err_DOMImplNotFound") );
return;
}
LSSerializer serializer = impl.createLSSerializer();
if( serializer.getDomConfig().canSetParameter( "format-pretty-print", Boolean.TRUE ) ) { //NOI18N
serializer.getDomConfig().setParameter( "format-pretty-print", Boolean.TRUE ); //NOI18N
}
LSOutput output = impl.createLSOutput();
output.setEncoding("UTF-8"); //NOI18N
output.setCharacterStream( io.getOut() );
serializer.write(doc, output);
io.getOut().println();
} catch( Exception ex ) {
ex.printStackTrace( io.getErr() );
} finally {
if( null != io ) {
io.getOut().close();
io.getErr().close();
}
}
}
/**
* Writes a Node out to a Writer using the DOM, level 3, Load/Save serializer. The written content is encoded using
* the encoding specified in the writer configuration.
*
* @param node the node to write out
* @param output the writer to write the XML to
* @param serializerParams parameters to pass to the {@link DOMConfiguration} of the serializer
* instance, obtained via {@link LSSerializer#getDomConfig()}. May be null.
*/
public static void writeNode(Node node, Writer output, Map<String, Object> serializerParams) {
DOMImplementationLS domImplLS = getLSDOMImpl(node);
LSSerializer serializer = getLSSerializer(domImplLS, serializerParams);
LSOutput serializerOut = domImplLS.createLSOutput();
serializerOut.setCharacterStream(output);
serializer.write(node, serializerOut);
}
/**
* Writes a Node out to an OutputStream using the DOM, level 3, Load/Save serializer. The written content
* is encoded using the encoding specified in the output stream configuration.
*
* @param node the node to write out
* @param output the output stream to write the XML to
* @param serializerParams parameters to pass to the {@link DOMConfiguration} of the serializer
* instance, obtained via {@link LSSerializer#getDomConfig()}. May be null.
*/
public static void writeNode(Node node, OutputStream output, Map<String, Object> serializerParams) {
DOMImplementationLS domImplLS = getLSDOMImpl(node);
LSSerializer serializer = getLSSerializer(domImplLS, serializerParams);
LSOutput serializerOut = domImplLS.createLSOutput();
serializerOut.setByteStream(output);
serializer.write(node, serializerOut);
}
@SuppressWarnings("unchecked")
private void getGroupings(Integer organisationId, HttpServletResponse response) throws IOException {
Document doc = OrganisationGroupServlet.docBuilder.newDocument();
Element groupsElement = doc.createElement("groups");
doc.appendChild(groupsElement);
List<OrganisationGrouping> groupings = userManagementService.findByProperty(OrganisationGrouping.class,
"organisationId", organisationId);
for (OrganisationGrouping grouping : groupings) {
Element groupingElement = doc.createElement("grouping");
groupingElement.setAttribute("id", grouping.getGroupingId().toString());
groupingElement.setAttribute("name", StringEscapeUtils.escapeXml(grouping.getName()));
groupsElement.appendChild(groupingElement);
for (OrganisationGroup group : grouping.getGroups()) {
Element groupElement = doc.createElement("group");
groupElement.setAttribute("id", group.getGroupId().toString());
groupElement.setAttribute("name", StringEscapeUtils.escapeXml(group.getName()));
groupingElement.appendChild(groupElement);
for (User user : group.getUsers()) {
Element userElement = doc.createElement("user");
userElement.setAttribute("id", user.getUserId().toString());
userElement.setAttribute("firstname", StringEscapeUtils.escapeXml(user.getFirstName()));
userElement.setAttribute("lastname", StringEscapeUtils.escapeXml(user.getLastName()));
groupElement.appendChild(userElement);
}
}
}
response.setContentType("text/xml");
response.setCharacterEncoding("UTF-8");
DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
LSSerializer lsSerializer = domImplementation.createLSSerializer();
LSOutput lsOutput = domImplementation.createLSOutput();
lsOutput.setEncoding("UTF-8");
lsOutput.setByteStream(response.getOutputStream());
lsSerializer.write(doc, lsOutput);
}
public String prettyPrintDOMResult(DOMResult dr) throws ClassNotFoundException, InstantiationException,
IllegalAccessException, ClassCastException
{
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS domImplementationLS = (DOMImplementationLS)registry.getDOMImplementation("LS");
StringWriter writer = new StringWriter();
LSOutput formattedOutput = domImplementationLS.createLSOutput();
formattedOutput.setCharacterStream(writer);
LSSerializer domSerializer = domImplementationLS.createLSSerializer();
domSerializer.getDomConfig().setParameter("format-pretty-print", true);
domSerializer.getDomConfig().setParameter("xml-declaration", false);
domSerializer.write(dr.getNode(), formattedOutput);
return writer.toString();
}
private String serializerWrite(Node xml, boolean pretty) throws Exception {
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS domImplementation = (DOMImplementationLS) registry.getDOMImplementation("LS");
StringWriter writer = new StringWriter();
LSOutput formattedOutput = domImplementation.createLSOutput();
formattedOutput.setCharacterStream(writer);
LSSerializer domSerializer = domImplementation.createLSSerializer();
domSerializer.getDomConfig().setParameter(DOM_FORMAT_PRETTY_PRINT, pretty);
domSerializer.getDomConfig().setParameter("xml-declaration", false);
domSerializer.write(xml, formattedOutput);
return writer.toString();
}
/** Returns a <code>LSOutput</code> instance.
* @param impl A <code>DOMImplementationLS</code> instance
* @param os Optional <code>OutputStream</code> instance
* @param encoding Optional character encoding, default is UTF-8
* @return A <code>LSOutput</code> instance
* @see <a href="http://www.w3.org/TR/2004/REC-DOM-Level-3-LS-20040407/">DOM Level 3 Load and Save Specification</a>
*/
public static LSOutput createLSOutput(DOMImplementationLS impl, OutputStream os, String encoding) {
LSOutput out = impl.createLSOutput();
if (os != null) {
out.setByteStream(os);
}
if (encoding != null) {
out.setEncoding(encoding);
}
return out;
}
/**
* Writes a Node out to a Writer using the DOM, level 3, Load/Save serializer. The written content is encoded using
* the encoding specified in the writer configuration.
*
* @param node the node to write out
* @param output the writer to write the XML to
* @param serializerParams parameters to pass to the {@link DOMConfiguration} of the serializer
* instance, obtained via {@link LSSerializer#getDomConfig()}. May be null.
*/
public static void writeNode(Node node, Writer output, Map<String, Object> serializerParams) {
DOMImplementationLS domImplLS = getLSDOMImpl(node);
LSSerializer serializer = getLSSerializer(domImplLS, serializerParams);
LSOutput serializerOut = domImplLS.createLSOutput();
serializerOut.setCharacterStream(output);
serializer.write(node, serializerOut);
}
/**
* from: https://stackoverflow.com/questions/139076/how-to-pretty-print-xml-from-java
* @param xml The string representation of the unformatted XML
* @return The string representation of the formatted XML
* @throws ClassCastException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws ClassNotFoundException
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
* @deprecated does it work with correct encoding?
*/
public static String formatXml(String xml) throws ClassNotFoundException, InstantiationException, IllegalAccessException, ClassCastException, SAXException, IOException, ParserConfigurationException {
// 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.
LSOutput lsOutput = impl.createLSOutput();
lsOutput.setEncoding("UTF-8");
StringWriter stringWriter = new StringWriter();
lsOutput.setCharacterStream(stringWriter);
writer.write(document, lsOutput);
return stringWriter.toString();
// return writer.writeToString(document);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
}
public static void serialize(final Element value, final JsonWriter sw) {
Document document = value.getOwnerDocument();
DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation();
LSSerializer serializer = domImplLS.createLSSerializer();
LSOutput lsOutput = domImplLS.createLSOutput();
lsOutput.setEncoding("UTF-8");
StringWriter writer = new StringWriter();
lsOutput.setCharacterStream(writer);
serializer.write(document, lsOutput);
StringConverter.serialize(writer.toString(), sw);
}
/**
* Serialize XML Node to string
* <p>
* Note: this method is supposed to be faster than the Transform version but the output control
* is limited. If node is Document node, it will output XML PI which sometimes we want to avoid.
*
* @param doc XML document
* @param node Node to be serialized
* @param encoding encoding for the output
* @return String representation of the Document
* @throws IOException
*/
public static String serializeToStringLS(Document doc, Node node, String encoding) throws IOException {
DOMImplementationLS domImpl = (DOMImplementationLS) doc.getImplementation();
LSSerializer lsSerializer = domImpl.createLSSerializer();
LSOutput output = domImpl.createLSOutput();
output.setEncoding(encoding);
StringWriter writer = new StringWriter();
output.setCharacterStream(writer);
lsSerializer.write(node, output);
writer.flush();
return writer.toString();
}
/**
* string value of document
*
* @return the string
*/
public final String stringValue()
{
if(log.isDebugEnabled())
{
log.debug("stringValue()");
}
if(document == null)
{
return this.xml.toString();
}
else
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
DOMImplementationRegistry registry = DOMImplementationRegistry
.newInstance();
DOMImplementationLS impl = (DOMImplementationLS) registry
.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
writer.getDomConfig().setParameter("format-pretty-print",
Boolean.TRUE);
LSOutput output = impl.createLSOutput();
output.setByteStream(out);
writer.write(document, output);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return out.toString();
}
}
private String toXML(Document doc) {
StringWriter result = new StringWriter();
DOMImplementation impl = documentBuilder.getDOMImplementation();
DOMImplementationLS feature = (DOMImplementationLS) impl.getFeature("LS", "3.0");
LSSerializer serializer = feature.createLSSerializer();
LSOutput lsoutput = feature.createLSOutput();
lsoutput.setCharacterStream(result);
lsoutput.setEncoding("UTF-8");
serializer.write(doc, lsoutput);
result.flush();
return result.toString();
}
/**
* Write a DOM Document to an output stream.
*
* @param doc
* The DOM Document to write.
* @param out
* The output stream.
*/
public static String writeDocumentToString(Document doc)
{
try
{
StringWriter sw = new StringWriter();
DocumentBuilder builder = dbFactory.newDocumentBuilder();
DOMImplementation impl = builder.getDOMImplementation();
DOMImplementationLS feature = (DOMImplementationLS) impl.getFeature("LS",
"3.0");
LSSerializer serializer = feature.createLSSerializer();
LSOutput output = feature.createLSOutput();
output.setCharacterStream(sw);
output.setEncoding("UTF-8");
serializer.write(doc, output);
sw.flush();
return sw.toString();
}
catch (Exception any)
{
log.warn("writeDocumentToString: " + any.toString());
return null;
}
}
/**
* Write a DOM Document to an output stream.
*
* @param doc
* The DOM Document to write.
* @param out
* The output stream.
*/
public static String writeDocumentToString(Document doc)
{
try
{
StringWriter sw = new StringWriter();
DocumentBuilderFactory factory
= DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
DOMImplementation impl = builder.getDOMImplementation();
DOMImplementationLS feature = (DOMImplementationLS) impl.getFeature("LS",
"3.0");
LSSerializer serializer = feature.createLSSerializer();
LSOutput output = feature.createLSOutput();
output.setCharacterStream(sw);
output.setEncoding("UTF-8");
serializer.write(doc, output);
sw.flush();
return sw.toString();
}
catch (Exception any)
{
log.warn("writeDocumentToString: " + any.toString());
return null;
}
}