如何在Jdom中同时更改读写XML的输出编码?

时间:2016-11-11 15:09:39

标签: java xml utf-8 jdom

我有这段代码,我想阅读并希望编写" prueba3.xml"同时,该文件是UTF8,但是当我写文件时,编码会改变并显示奇怪的字符,虽然我已添加format.setEncoding("UTF-8"),但它没有正确执行。是否可以使用jdom SAXBuilder将输出编码更改为UTF8?

输入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>

问候并感谢您的时间。

1 个答案:

答案 0 :(得分: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);
}

...它将输出用作字节流,系统的默认编码不会干扰输出。

(P.S。没有理由两次分配xmlOutput个实例。)