2014-11-05 97 views
2

由於打開/加載生成的xml文件不正確(「無效的1字節UTF-8序列的字節1」),所以出現了一些問題。 我已經搜索了一些解決方案,改變了我的代碼用於獲取設計如下:jdom 2.0.5 XML解析錯誤:格式不正確

System.out.println("Which Design-File shall be modified? Please enter: [file].xml"); 

    String file = "file.xml"; 

    // generate JDOM Document 
    SAXBuilder builder = new SAXBuilder(); 
    try { 
     // getting rid of the UTF8 problem when reading the modified xml file 
     InputStream inputStream= new FileInputStream(file)   
     Reader reader = new InputStreamReader(inputStream,"UTF-8"); 

     InputSource is = new InputSource(reader); 
     is.setEncoding("UTF-8"); 

     Document doc = builder.build(is); 
    } 
    catch (JDOMException e) { 
     e.printStackTrace(); 
    } 
    catch (IOException e) { 
     e.printStackTrace(); 
    } 

改變設計後,我用的XMLOutputter寫如下:

String fileNew = "file_modified.xml"; 
    FileWriter writer; 
    try { 
     Format format = Format.getPrettyFormat(); 
     format.setEncoding("UTF-8"); 
     writer = new FileWriter(fileNew); 
     XMLOutputter outputter = new XMLOutputter(format); 
     outputter.output(doc, writer); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

是否有人有解決我的問題?我真的認爲這些代碼行可以解決我的問題,但是當我將它加載到Firefox中時,它仍然表示它沒有正確形成:/。

回答

1

XMLOutputter documentation

Warning: When outputting to a Writer , make sure the writer's encoding matches the encoding setting in the Format object. This ensures the encoding in which the content is written (controlled by the Writer configuration) matches the encoding placed in the document's XML declaration (controlled by the XMLOutputter). Because a Writer cannot be queried for its encoding, the information must be passed to the Format manually in its constructor or via the Format.setEncoding(java.lang.String) method. The default encoding is UTF-8.

JDOM使用Format實例的編碼,以確定用於OutputStreams雖然編碼,因此,編寫代碼的建議方法是:

try (FileOutputStream fos = new FileOutputStream(fileNew)) { 
    Format format = Format.getPrettyFormat(); 
    format.setEncoding("UTF-8"); 
    XMLOutputter outputter = new XMLOutputter(format); 
    outputter.output(doc, fos); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

使用OutputStreams而不是Writers將確保使用的實際編碼應用於文件,而不是平臺默認值。

+0

非常感謝!這解決了我的問題 – hofmanic 2014-11-05 15:38:48

相關問題