2014-11-05 61 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

相关问题