【发布时间】:2012-07-03 07:29:39
【问题描述】:
我一直试图在我的代码中删除所有 com.sun.org.apache.xml.internal 包,用稳定的替代品替换它们。
这是我替换的一种方法...
import com.sun.org.apache.xml.internal.serialize.LineSeparator;
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
...
...
/**
* @param source
* @param target
* @throws IOException
*/
protected static void serialize( Document source, Writer target ) throws IOException
{
OutputFormat outputFormat = new OutputFormat( (Document) source );
outputFormat.setLineSeparator( LineSeparator.Windows );
// format.setIndenting(true);
outputFormat.setLineWidth( 0 );
outputFormat.setPreserveSpace( true );
XMLSerializer serializer = new XMLSerializer( target, outputFormat );
serializer.asDOMSerializer();
serializer.serialize( source );
} // end serialize
这是我找到的另一种选择......
/**
* @param source
* @param target
* @throws IOException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws ClassNotFoundException
* @throws ClassCastException
*/
protected static void serialize( Document source, Writer target ) throws Exception
{
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation( "LS" );
LSSerializer writer = impl.createLSSerializer();
target.write( writer.writeToString(source) );
} // end serialize
但是,它显示了正在生成的 xml 中的差异。
它创造了
<?xml version="1.0" encoding="UTF-16"?>
如何修改它以创建 UTF-8?
【问题讨论】:
-
网上有很多sn-ps的代码读写XML。
org.w3c.Document.getXmlEncoding()会在阅读后给出“UTF-16”。但是没有设置器,因为写作使用了应该在encoding属性中修补的编码。