一般是用OutputStreamWriter输出你需要的encoding
XML文件的encoding, 写Transformer的属性,参考http://www.rgagnon.com/javadetails/java-0481.html
譬如Element root = doc.getDocumentElement();ProcessingInstruction xmlstylesheet 
 = doc.createProcessingInstruction("xml-stylesheet",
 "type=\"text/xsl\" href=\"myxsl.xsl\"");
 doc.insertBefore(xmlstylesheet, root);TransformerFactory xformFactory 
       = TransformerFactory.newInstance();  
      Transformer idTransform = xformFactory.newTransformer();
      idTransform.setOutputProperty(OutputKeys.ENCODING,"GB2312");
      idTransform.setOutputProperty(OutputKeys.STANDALONE,"yes");
      Source input = new DOMSource(doc);
      Result output = new StreamResult(System.out);
      idTransform.transform(input, output);

解决方案 »

  1.   

    谢谢帮助,但是有个问题,当我输出utf-16编码的时候文档不能被ie,xmlspy识别,说格式不对。        Document doc=....
            Element r=doc.createElement("root");
            r.setAttribute("sw","ss");
            doc.appendChild(r);
            Element s1=doc.createElement("s1");TransformerFactory xformFactory
    = TransformerFactory.newInstance();
    Transformer idTransform = xformFactory.newTransformer();idTransform.setOutputProperty(OutputKeys.ENCODING,"utf-16");Source input = new DOMSource(doc);
    Result output = new StreamResult(new FileOutputStream("c:\\1.xml"));
    idTransform.transform(input, output);
      

  2.   

    GB2312和GBK都是支持中文的编码格式!
    一般都用GBK的
      

  3.   

    为什么不能输出正确的utf-16编码?
      

  4.   

    谢谢帮助,但是有个问题,当我输出utf-16编码的时候文档不能被ie,xmlspy识别,说格式不对。Document doc=....
    Element r=doc.createElement("root");
    r.setAttribute("sw","ss");
    doc.appendChild(r);
    Element s1=doc.createElement("s1");TransformerFactory xformFactory
    = TransformerFactory.newInstance();
    Transformer idTransform = xformFactory.newTransformer();idTransform.setOutputProperty(OutputKeys.ENCODING,"utf-16");Source input = new DOMSource(doc);
    Result output = new StreamResult(new FileOutputStream("c:\\1.xml"));
    idTransform.transform(input, output);////////////////////请注意此问题!!!!!!!!!