该XMLWriter
接口具有所需编码属性的设置器,但当前的实现RDFXMLRenderer
不允许设置此属性。(你可以称之为错误——如果你想提出问题,跟踪器就在这里——修复就在这里)
正如您所说,使用 XSLT 的一种解决方法是矫枉过正,最终可能会很慢。
由于更改的范围非常有限,我要做的是编写一个拦截器来覆盖一行。像这样的东西(未经测试):
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import org.semanticweb.owlapi.io.WriterDocumentTarget;
public class TestUTF8 {
public static void main(String[] args) {
try (Writer w = new OutputStreamWriter(new FileOutputStream(""), StandardCharsets.UTF_8)) {
WriterDocumentTarget t = new WriterDocumentTarget(new InterceptingWriter(w));
// save the ontology here
} catch (IOException e) {
e.printStackTrace();
}
}
}
class InterceptingWriter extends Writer {
private static final String XML_VERSION_1_0 = "<?xml version=\"1.0\"?>\n";
private static final String XML_VERSION_1_0_ENCODING_UTF_8 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
private Writer wrapped;
boolean beginning = true;
public InterceptingWriter(Writer wrapped) {
this.wrapped = wrapped;
}
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
wrapped.write(cbuf, off, len);
}
@Override
public void flush() throws IOException {
wrapped.flush();
}
@Override
public void close() throws IOException {
wrapped.close();
}
@Override
public void write(String str, int off, int len) throws IOException {
if (str.equals(XML_VERSION_1_0) && off == 0 && len == XML_VERSION_1_0.length()) {
wrapped.write(XML_VERSION_1_0_ENCODING_UTF_8, 0, XML_VERSION_1_0_ENCODING_UTF_8.length());
} else {
wrapped.write(str, off, len);
}
}
@Override
public void write(String str) throws IOException {
if (str.equals(XML_VERSION_1_0)) {
super.write(XML_VERSION_1_0_ENCODING_UTF_8);
} else {
super.write(str);
}
}
}