2014-11-05 3 views
2

У меня возникли проблемы при открытии/загрузке сгенерированного xml-файла, потому что он плохо сформирован («Недопустимый байт 1 из 1-байтовой последовательности UTF-8»). я уже искал какое-то решение и изменил код для получения конструкции следующим образом:jdom 2.0.5 Ошибка XML-Parsing: не сформирована

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(); 
    } 

ли кто-то есть решение для моей проблемы? Я действительно думал, что эти codelines будут решать мою проблему, но когда я загружаю его в 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