📄 jaxpxslt4.html
字号:
<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> <meta http-equiv="Content-Style-Type" content="text/css" /> <title>Writing Out a DOM as an XML File</title> <link rel="StyleSheet" href="document.css" type="text/css" media="all" /> <link rel="StyleSheet" href="catalog.css" type="text/css" media="all" /> <link rel="Table of Contents" href="J2EETutorialTOC.html" /> <link rel="Previous" href="JAXPXSLT3.html" /> <link rel="Next" href="JAXPXSLT5.html" /> <link rel="Index" href="J2EETutorialIX.html" /> </head> <body> <table width="550" summary="layout" id="SummaryNotReq1"> <tr> <td align="left" valign="center"> <font size="-1"> <a href="http://java.sun.com/j2ee/1.4/download.html#tutorial" target="_blank">Download</a> <br> <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/information/faq.html" target="_blank">FAQ</a> <br> <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/information/history.html" target="_blank">History</a> </td> <td align="center" valign="center"><a accesskey="p" href="JAXPXSLT3.html"><img id="LongDescNotReq1" src="images/PrevArrow.gif" width="26" height="26" border="0" alt="Prev" /></a><a accesskey="c" href="J2EETutorialFront.html"><img id="LongDescNotReq1" src="images/UpArrow.gif" width="26" height="26" border="0" alt="Home" /></a><a accesskey="n" href="JAXPXSLT5.html"><img id="LongDescNotReq3" src="images/NextArrow.gif" width="26" height="26" border="0" alt="Next" /></a><a accesskey="i" href="J2EETutorialIX.html"></a> </td> <td align="right" valign="center"> <font size="-1"> <a href="http://java.sun.com/j2ee/1.4/docs/api/index.html" target="_blank">API</a> <br> <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/information/search.html" target="_blank">Search</a> <br> <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/information/sendusmail.html" target="_blank">Feedback</a></font> </font> </td> </tr> </table> <img src="images/blueline.gif" width="550" height="8" ALIGN="BOTTOM" NATURALSIZEFLAG="3" ALT="Divider"> <blockquote><a name="wp64603"> </a><h2 class="pHeading1">Writing Out a DOM as an XML File</h2><a name="wp64604"> </a><p class="pBody">Once you have constructed a DOM, either by parsing an XML file or building it programmatically, you frequently want to save it as XML. This section shows you how to do that using the Xalan transform package. </p><a name="wp64605"> </a><p class="pBody">Using that package, you'll create a transformer object to wire a <code class="cCode">DomSource</code> to a <code class="cCode">StreamResult</code>. You'll then invoke the transformer's <code class="cCode">transform()</code> method to write out the DOM as XML data.</p><a name="wp64607"> </a><h3 class="pHeading2">Reading the XML</h3><a name="wp64608"> </a><p class="pBody">The first step is to create a DOM in memory by parsing an XML file. By now, you should be getting pretty comfortable with the process.</p><hr><a name="wp64609"> </a><p class="pNote">Note: The code discussed in this section is in <code class="cCode"><a href="../examples/jaxp/xslt/samples/TransformationApp01.java" target="_blank">TransformationApp01.java</a></code>. </p><hr><a name="wp64610"> </a><p class="pBody">The code below provides a basic template to start from. (It should be familiar. It's basically the same code you wrote at the start of the DOM tutorial. If you saved it then, that version should be pretty much the equivalent of what you see below.)</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException;<a name="wp64611"> </a>import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.w3c.dom.Document;import org.w3c.dom.DOMException;import java.io.*;public class TransformationApp { static Document document; public static void main(String argv[]) { if (argv.length != 1) { System.err.println ( "Usage: java TransformationApp filename"); System.exit (1); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //factory.setNamespaceAware(true); //factory.setValidating(true); try { File f = new File(argv[0]); DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.parse(f); } catch (SAXParseException spe) { // Error generated by the parser System.out.println("\n** Parsing error" + ", line " + spe.getLineNumber() + ", uri " + spe.getSystemId()); System.out.println(" " + spe.getMessage() ); // Use the contained exception, if any Exception x = spe; if (spe.getException() != null) x = spe.getException(); x.printStackTrace(); } catch (SAXException sxe) { // Error generated by this application // (or a parser-initialization error) Exception x = sxe; if (sxe.getException() != null) x = sxe.getException(); x.printStackTrace(); } catch (ParserConfigurationException pce) { // Parser with specified options can't be built pce.printStackTrace(); } catch (IOException ioe) { // I/O error ioe.printStackTrace(); } } // main }<a name="wp66720"> </a></pre></div><a name="wp64614"> </a><h3 class="pHeading2">Creating a Transformer</h3><a name="wp64615"> </a><p class="pBody">The next step is to create a transformer you can use to transmit the XML to <code class="cCode">System.out</code>. </p><hr><a name="wp64616"> </a><p class="pNote">Note: The code discussed in this section is in <code class="cCode"><a href="../examples/jaxp/xslt/samples/TransformationApp02.java" target="_blank">TransformationApp02.java</a></code>. The file it runs on is <code class="cCode"><a href="../examples/jaxp/xslt/samples/slideSample01.xml" target="_blank">slideSample01.xml</a></code>. The output is in <code class="cCode"><a href="../examples/jaxp/xslt/samples/TransformationLog02.txt" target="_blank">TransformationLog02.txt</a></code>. (The browsable versions are <code class="cCode"><a href="../examples/jaxp/xslt/samples/slideSample01-xml.html" target="_blank">slideSample01-xml.html</a></code> and <code class="cCode"><a href="../examples/jaxp/xslt/samples/TransformationLog02.html" target="_blank">TransformationLog02.html</a></code>.)</p><hr><a name="wp64617"> </a><p class="pBody"> Start by adding the import statements highlighted below:</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative"><code class="cCodeBold">import javax.xml.transform.Transformer;import javax.xml.transform.TransformerFactory;import javax.xml.transform.TransformerException;import javax.xml.transform.TransformerConfigurationException;import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; </code>import java.io.*;<a name="wp64618"> </a></pre></div><a name="wp64619"> </a><p class="pBody">Here, you've added a series of classes which should now be forming a standard pattern: an entity (<code class="cCode">Transformer</code>), the factory to create it (<code class="cCode">TransformerFactory</code>), and the exceptions that can be generated by each. Since a transformation always has a <span style="font-style: italic">source</span> and a <span style="font-style: italic">result</span>, you then imported the classes necessary to use a DOM as a source (<code class="cCode">DomSource</code>), and an output stream for the result (<code class="cCode">StreamResult</code>).</p><a name="wp64620"> </a><p class="pBody">Next, add the code to carry out the transformation:</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">try { File f = new File(argv[0]); DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.parse(f);<code class="cCodeBold"> // Use a Transformer for output TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(System.out); transformer.transform(source, result);</code><a name="wp64621"> </a></pre></div><a name="wp64622"> </a><p class="pBody">Here, you created a transformer object, used the DOM to construct a source object, and used <code class="cCode">System.out</code> to construct a result object. You then told the transformer to operate on the source object and output to the result object.</p><a name="wp64624"> </a><p class="pBody">In this case, the "transformer" isn't actually changing anything. In XSLT terminology, you are using the <span style="font-style: italic">identity transform</span>, which means that the "transformation" generates a copy of the source, unchanged. </p><hr><a name="wp85638"> </a><p class="pNote">Note: You can specify a variety of output properties for transformer objects, as defined in the W3C specification at <code class="cCode"><a href="http://www.w3.org/TR/xslt#output" target="_blank">http://www.w3.org/TR/xslt#output</a></code>. For example, to get indented output, you can invoke:<br /><code class="cCode"> transformer.setOutputProperty("indent", "yes");</code>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -