XMLDocument output XML file solves the solvement of Cast Exception

xiaoxiao2021-03-06  72

Recently I saw a lot of articles introducing XML from the Internet, when the XML file is output, the sample code is:

...

// output XML document to the specified file FileOutputStream outStream = new FileOutputStream (outFile); OutputStreamWriter outWriter = new OutputStreamWriter (outStream); ((org.apache.crimson.tree.XmlDocument) doc) .write (outWriter, "GB2312" Outwriter.close (); outstream.close ();

...

Unfortunately, this code can not pass ... will appear CASS CAST EXCEPTION Error!

The author seems to have not realized.

After my research, I proposed a solution. Use Transformer to output an XML file. Complete code

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 (transformerExcection e) {E.PrintStackTrace ();}}

After I compiled in WinXP, JDK1.4, the package to include is:

Import javax.xml.parsers. *; // XML parser interface import org.w3c.dom. *; // XML DOM implementation

Import javax.xml.transform. *; import javax.xml.transform.dom.domsource; import javax.xml.transform.stream.streamResult;

Correspondingly, the error of the error should be corrected:

// The XML document output to the specified file FileOutputStream outStream = new FileOutputStream (outFile); OutputStreamWriter outWriter = new (outStream) OutputStreamWriter; // error class cast exception // ((org.apache.crimson.tree.XmlDocument) doc ) .write (Outwriter, "GB2312"); // exchange additional output XML method CallWriteXMLFile (DOC, OUTWRITER, "GB2312"); outstream.close (); outstream.close (); Outstream.close ();

and so,

转载请注明原文地址:https://www.9cbs.com/read-121243.html

New Post(0)