下面列出了怎么用org.w3c.dom.ls.LSSerializer的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);
}
}
public static String elementToString(Element element) {
try {
if (element == null) {
/* return an empty string because, the other way around works the same,
where if we give a empty string as the XML, we get a null element
from "stringToElement" */
return "";
}
Document document = element.getOwnerDocument();
DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation();
LSSerializer serializer = domImplLS.createLSSerializer();
//by default its true, so set it to false to get String without xml-declaration
serializer.getDomConfig().setParameter(XML_DECLARATION, false);
return serializer.writeToString(element);
} catch (Exception e) {
log.error("Error while convering element to string: " + e.getMessage(), e);
return null;
}
}
/**
* Obtain a the DOM, level 3, Load/Save serializer {@link LSSerializer} instance from the
* given {@link DOMImplementationLS} instance.
*
* <p>
* The serializer instance will be configured with the parameters passed as the <code>serializerParams</code>
* argument. It will also be configured with an {@link LSSerializerFilter} that shows all nodes to the filter,
* and accepts all nodes shown.
* </p>
*
* @param domImplLS the DOM Level 3 Load/Save implementation to use
* @param serializerParams parameters to pass to the {@link DOMConfiguration} of the serializer
* instance, obtained via {@link LSSerializer#getDomConfig()}. May be null.
*
* @return a new LSSerializer instance
*/
public static LSSerializer getLSSerializer(DOMImplementationLS domImplLS, Map<String, Object> serializerParams) {
LSSerializer serializer = domImplLS.createLSSerializer();
serializer.setFilter(new LSSerializerFilter() {
public short acceptNode(Node arg0) {
return FILTER_ACCEPT;
}
public int getWhatToShow() {
return SHOW_ALL;
}
});
if (serializerParams != null) {
DOMConfiguration serializerDOMConfig = serializer.getDomConfig();
for (String key : serializerParams.keySet()) {
serializerDOMConfig.setParameter(key, serializerParams.get(key));
}
}
return serializer;
}
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);
}
/**
* 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());
}
}
/**
* 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);
}
}
/**
* Check for DOMErrorHandler handling DOMError. Before fix of bug 4890927
* DOMConfiguration.setParameter("well-formed",true) throws an exception.
*
* @throws Exception If any errors occur.
*/
@Test
public void testCreateNewItem2Sell() throws Exception {
String xmlFile = XML_DIR + "novelsInvalid.xml";
Document document = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(xmlFile);
document.getDomConfig().setParameter("well-formed", true);
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
MyDOMOutput domOutput = new MyDOMOutput();
domOutput.setByteStream(System.out);
LSSerializer writer = impl.createLSSerializer();
writer.write(document, domOutput);
}
/**
* Check for DOMErrorHandler handling DOMError. Before fix of bug 4896132
* test throws DOM Level 1 node error.
*
* @throws Exception If any errors occur.
*/
@Test
public void testCreateNewItem2SellRetry() throws Exception {
String xmlFile = XML_DIR + "accountInfo.xml";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document document = dbf.newDocumentBuilder().parse(xmlFile);
DOMConfiguration domConfig = document.getDomConfig();
MyDOMErrorHandler errHandler = new MyDOMErrorHandler();
domConfig.setParameter("error-handler", errHandler);
DOMImplementationLS impl =
(DOMImplementationLS) DOMImplementationRegistry.newInstance()
.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
MyDOMOutput domoutput = new MyDOMOutput();
domoutput.setByteStream(System.out);
writer.write(document, domoutput);
document.normalizeDocument();
writer.write(document, domoutput);
assertFalse(errHandler.isError());
}
/**
* 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;
}
/**
* 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);
}
}
/**
* `
* 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 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);
}
}
/**
* Saves the process configuration.
*/
private void saveConfiguration(Document docXMLConfig) {
String fileToSaveConf = properties.getSaveRemoteConfig();
if (fileToSaveConf.length() > 0 && docXMLConfig != null) {
log.info("saveConfiguration - saving the process configuration XML in a file " + fileToSaveConf + " due to user request");
File file = new File(fileToSaveConf);
if (file.isDirectory() || !fileToSaveConf.endsWith(".xml")) {
throw new RuntimeException("Path to which to save remote config must end with '.xml'");
}
try {
DOMImplementationLS domImplementation = (DOMImplementationLS) docXMLConfig.getImplementation();
LSSerializer lsSerializer = domImplementation.createLSSerializer();
lsSerializer.writeToURI(docXMLConfig, file.toURI().toURL().toString());
} catch (java.io.IOException ex) {
log.error("saveConfiguration - Could not save the configuration to the file " + fileToSaveConf, ex);
}
}
}
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);
}
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 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 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);
}
}
/***
* 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;
}
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;
}
}
/**
* `
* 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);
}
}
public static String format(final String in) {
try {
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
final DocumentBuilder db = dbf.newDocumentBuilder();
final InputSource is = new InputSource(new StringReader(in));
final Document document = db.parse(is);
final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
final DOMImplementationLS impl = DOMImplementationLS.class.cast(registry.getDOMImplementation("XML 3.0 LS 3.0"));
if (impl == null) {
return in;
}
final LSSerializer serializer = impl.createLSSerializer();
if (serializer.getDomConfig().canSetParameter("format-pretty-print", Boolean.TRUE)) {
serializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
final LSOutput lsOutput = impl.createLSOutput();
lsOutput.setEncoding("UTF-8");
final StringWriter stringWriter = new StringWriter();
lsOutput.setCharacterStream(stringWriter);
serializer.write(document, lsOutput);
return stringWriter.toString().replace("\"UTF-8\"?><", "\"UTF-8\"?>\n<");
}
return in;
} catch (final Throwable t) {
return in; // just to be more sexy so ignore it and use ugly xml
}
}
/**
* 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;
}
}
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 serializeTransformElement(Element xformEl) throws DOMException, LSException {
Document document = xformEl.getOwnerDocument();
DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation();
LSSerializer serializer = domImplLS.createLSSerializer();
// serializer.getDomConfig().setParameter("namespaces", true);
// serializer.getDomConfig().setParameter("namespace-declarations", true);
serializer.getDomConfig().setParameter("canonical-form", false);
serializer.getDomConfig().setParameter("xml-declaration", false);
String str = serializer.writeToString(xformEl);
return str;
}
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);
}
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);
}