2016-11-11 29 views
0

我有這段代碼,我想讀取並且想同時寫「prueba3.xml」,文件是UTF8但是當我寫這個文件時,編碼會改變並顯示奇怪的字符,雖然我已經加了format.setEncoding("UTF-8") ,它沒有正確執行。是否有可能使用jdom SAXBuilder將輸出編碼更改爲UTF8?如何在Jdom中同時更改讀寫XML的輸出編碼?

輸入XML:

<?xml version="1.0" encoding="UTF-8"?> 
<prueba> 
    <reg id="576340"> 
     <dato cant="856" id="6" val="-1" num="" desc="ñápás" /> 
     <dato cant="680" id="1" val="-1" num="" desc="résd" /> 
     <dato cant="684" id="5" val="-1" num="" desc="..да и вообем" /> 
     <dato cant="1621" id="1" val="-1" num="" desc="hi" /> 
     <dato cant="1625" id="5" val="-1" num="" desc="Hola" /> 
    </reg> 
</prueba> 

這是代碼:

public static void main(String[] args) throws FileNotFoundException, JDOMException, IOException 
{ 
    //Se crea un SAXBuilder para poder parsear el archivo 
    File xml = new File("c:\\prueba3.xml"); 
    Document doc = (Document) new SAXBuilder().build(xml); 

    Element raiz = doc.getRootElement(); 
    //Recorremos los hijos de la etiqueta raíz 
    List articleRow = raiz.getChildren("reg"); 

    for (int i = 0; i < articleRow.size(); i++) { 

     Element row = (Element) articleRow.get(i); 
     List images = row.getChildren("dato"); 

     for (int j = 0; j < images.size(); j++) { 

      Element row2 = (Element) images.get(j); 
      String texto = row2.getAttributeValue("desc") ; 
      String id = row2.getAttributeValue("id"); 

        if ((texto != null) && (texto !="") && (id.equals("1"))){ 
        row2.getAttribute("desc").setValue("Raúl").toString(); 
        } 
     } 

     Format format = Format.getRawFormat(); 
     format.setEncoding("UTF-8"); 
     XMLOutputter xmlOutput = new XMLOutputter(format); 
     xmlOutput = new XMLOutputter(format); 
     xmlOutput.output(doc, new FileWriter("c:\\prueba3.xml")); 
    } 

    System.out.println("fin"); 
} 

輸出XML:

<?xml version="1.0" encoding="UTF-8"?> 
<prueba> 
    <reg id="576340"> 
     <dato cant="856" id="6" val="-1" num="" desc="s" /> 
     <dato cant="680" id="1" val="-1" num="" desc="Ra/> 
     <dato cant="684" id="5" val="-1" num="" desc="..?? ? ??????" /> 
     <dato cant="1621" id="1" val="-1" num="" desc="Ra/> 
     <dato cant="1625" id="5" val="-1" num="" desc="Hola" /> 
</reg> 
</prueba> 

問候,並感謝您的時間。

回答

0

這是使用JDOM時遇到的一個比較常見的問題 - 尤其是在使用非拉丁字母的國家/地區。在某些意義上,我很遺憾在JDOM中始終保持使用Writer輸出。

查看的XMLOutputter的JavaDoc太:http://www.jdom.org/docs/apidocs/org/jdom2/output/XMLOutputter.html

的問題是,FileWriter使用系統的默認編碼從Writer轉換到底層字節數據。 JDOM無法控制該轉換。

如果你改變的代碼行:

xmlOutput.output(doc, new FileWriter("c:\\prueba3.xml")); 

使用的OutputStream而不是Writer

try (OutputStream fos = new FileOutputStream("c:\\prueba3.xml")) { 
    xmlOutput.output(doc, fos); 
} 

...它將使用輸出作爲一個字節-stream,系統的默認編碼不會干擾輸出。

(附註:我們沒有理由兩次分配xmlOutput實例。)

+0

您好,感謝了很多,現在它工作正常,現在簡單看來,你給我解釋了XD。問候。 –