XmlDocument输出XML文件出现cast exception的解决

类别:Java 点击:0 评论:0 推荐:

最近从网上看到很多介绍XML的文章,输出XML文件时候,示例代码为:

...

//把XML文档输出到指定的文件
    FileOutputStream outStream = new FileOutputStream(outFile);
    OutputStreamWriter outWriter = new OutputStreamWriter(outStream);
 ( ( org.apache.crimson.tree.XmlDocument) doc).write(outWriter, "GB2312");
    outWriter.close();
    outStream.close();

...

 

很遗憾,这段代码是通过不了的...会出现Class Cast Exception错误!

而作者看来并没有意识到.

 

经过我的研究,提出了解决的办法.采用Transformer来输出XML文件。完整代码为

  public static void callWriteXmlFile(Document doc, Writer w,
                                      String encoding) {
    try {
      // Prepare the DOM document for writing
      Source source = new DOMSource(doc);

      // Prepare the output file
      Result result = new StreamResult(w);

      // Write the DOM document to the file
      Transformer xformer = TransformerFactory.newInstance()
          .newTransformer();
      xformer.setOutputProperty(OutputKeys.ENCODING, encoding);
      xformer.transform(source, result);

    }
    catch (TransformerConfigurationException e) {
      e.printStackTrace();
    }
    catch (TransformerException e) {
      e.printStackTrace();
    }
  }

经过我在winxp,jdk1.4环境下编译通过.要包含的包为:

import javax.xml.parsers.*; //XML解析器接口
import org.w3c.dom.*; //XML的DOM实现

import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

对应的,出错的代码应该改正为:

//把XML文档输出到指定的文件
    FileOutputStream outStream = new FileOutputStream(outFile);
    OutputStreamWriter outWriter = new OutputStreamWriter(outStream);
    //出现错误class cast exception
//    ( ( org.apache.crimson.tree.XmlDocument) doc).write(outWriter, "GB2312");
    //换另外的输出xml方法
    callWriteXmlFile(doc, outWriter, "GB2312");
    outWriter.close();
    outStream.close();

所以,

本文地址:http://com.8s8s.com/it/it15819.htm