【问题标题】:Serialize a DOM document in UTF-8以 UTF-8 序列化 DOM 文档
【发布时间】: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 属性中修补的编码。

标签: java dom utf-8 utf-16


【解决方案1】:

我认为你必须使用LSOutput:

LSOutput domOutput = impl.createLSOutput();
domOutput.setEncoding(StandardCharsets.UTF_8.name());
domOutput.setCharacterStream(stringWriter);

更多详情请参见此处的回复:

Change the com.sun.org.apache.xml.internal.serialize.XMLSerializer & com.sun.org.apache.xml.internal.serialize.OutputFormat

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    • 1970-01-01
    • 2016-05-06
    • 2011-04-02
    • 1970-01-01
    • 2020-01-20
    • 1970-01-01
    相关资源
    最近更新 更多