gpt4 book ai didi

java - 以 UTF-8 序列化 DOM 文档

转载 作者:行者123 更新时间:2023-12-01 05:15:22 27 4
gpt4 key购买 nike

我一直在尝试删除代码中的所有 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?

最佳答案

我认为你必须使用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

关于java - 以 UTF-8 序列化 DOM 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11301210/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com