在使用java 1.6进行编译时,使用com.sun.org.apache.xml.internal.serialize.XMLSerializer和com.sun.org.apache.xml.internal.serialize.OutputFormat会导致一些错误.
我找到的解决方案是在添加xerces后使用org.apache.xml.serialize.XMLSerializer和org.apache.xml.serialize.OutputFormat.
问题是不推荐使用这些类.如果不触及代码,我可以使用什么来替换它们?
日Thnx
这是我使用的依赖:
<dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.9.1</version>
</dependency>
解决方法:
我们可以使用org.w3c.dom.ls包中的LSSerializer类
public String toXML(Node source) {
String subscrXML=null;
StringWriter stringWriter=new StringWriter();
try {
//Get the implementations
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impls = (DOMImplementationLS)registry.getDOMImplementation("LS");
//Prepare the output
LSOutput domOutput = impls.createLSOutput();
domOutput.setEncoding(java.nio.charset.Charset.defaultCharset().name());
domOutput.setCharacterStream(stringWriter);
domOutput.setEncoding(ENCODING);
//Prepare the serializer
LSSerializer domWriter = impls.createLSSerializer();
DOMConfiguration domConfig = domWriter.getDomConfig();
domConfig.setParameter("format-pretty-print", true);
domConfig.setParameter("element-content-whitespace", true);
domWriter.setNewLine("\r\n");
domConfig.setParameter("cdata-sections", Boolean.TRUE);
//And finaly, write
domWriter.write(source, domOutput);
subscrXML = domOutput.getCharacterStream().toString();
DOMStringList dsl=domConfig.getParameterNames();
System.out.println(subscrXML);
/*
// Just for curiosity....
for(int i=0;i<dsl.getLength();i){
System.out.println(dsl.item(i)" = ["domConfig.getParameter(dsl.item(i))"]");
}*/
} catch (Exception e) {
e.printStackTrace();
}
return subscrXML;
}