XMLWriter
接口有一個用於所需編碼屬性的setter,但RDFXMLRenderer
的當前實現不允許設置此屬性。 (你可以稱這是一個錯誤 - 如果你想提出的一個問題,跟蹤器是here - 修復是here)
與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);
}
}
}
manager.saveOntology(本體論,(新RDFXMLDocumentFormatFactory())createFormat(),新WriterOutputStream(作家,Charset.forName( 「UTF-8」))); – Galigator
這不會將'encoding =「UTF-8」'添加到輸出XML的標頭中。 –
添加屬性不會使輸出文件爲UTF-8,它只是聲明它。默認情況下,OWLAPI已經使用UTF-8編碼進行保存。 – Ignazio