jdom 2.0.5 XML-Parsing错误:格式不正确

时间:2014-11-05 10:10:58

标签: xml utf-8 jdom

通过打开/加载生成的xml文件我遇到了一些问题,因为它没有很好地形成(" 1字节UTF-8序列的无效字节1")。 我已经搜索了一些解决方案并更改了我的代码以获得如下设计:

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 个答案:

答案 0 :(得分:1)

来自XMLOutputter documentation

  

警告:输出到Writer时,请确保编写者的编码   匹配Format对象中的编码设置。这确保了   编写内容的编码(由Writer控制   配置)匹配文档XML中的编码   声明(由XMLOutputter控制)。因为Writer不能   要查询其编码,必须将信息传递给   在其构造函数中手动格式化或通过   Format.setEncoding(java.lang.String)方法。默认编码是   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将确保使用的实际编码应用于文件,而不是平台默认值。