2017-03-08 23 views
1

我有一個需要使用RDFXMLDocumentFormat保存到文件的OWLOntology,我想將其編碼爲UTF-8。具體來說,我想該文件的頂部有以下幾點:在OWLAPI中,如何在頭文件中編寫包含UTF-8編碼的RDF/XML

<?xml version="1.0" encoding="UTF-8"?> 

當然,我可以在OWLOntology(使用RDFXMLDocumentFormat)保存到一個ByteArrayOutputStream,使用字符串從輸出流中創建一個XML文檔,然後使用編碼設置爲UTF-8的Transformer將該XML文檔寫入文件;然而,對於大型本體來說,它會表現得很差,因爲它會被寫入輸出流,然後重新讀入,然後再次寫出。

在API中,我確實看過了RDFXMLWriter,它允許我設置編碼,看起來好像RDFXMLStorer在存儲本體時使用它。但是,我不明白我如何訪問RDFXMLWriter來指定所需的編碼。

有沒有辦法做到這一點,我失蹤了?

+0

manager.saveOntology(本體論,(新RDFXMLDocumentFormatFactory())createFormat(),新WriterOutputStream(作家,Charset.forName( 「UTF-8」))); – Galigator

+0

這不會將'encoding =「UTF-8」'添加到輸出XML的標頭中。 –

+0

添加屬性不會使輸出文件爲UTF-8,它只是聲明它。默認情況下,OWLAPI已經使用UTF-8編碼進行保存。 – Ignazio

回答

1

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); 
     } 
    } 
} 
相關問題