Java Reference
In-Depth Information
You want to convert an XML document to another format, for example to HTML.
Solution
Use the javax.xml.transform package to transform an XML document to anoth-
er document format.
The following code demonstrates how to read a source document, apply an Extens-
ible Stylesheet Language (XSL) transform file, and produce the transformed, new doc-
ument. Use the sample code from the
org.java8recipes.chapter20.recipe20_3.TransformXml class to
read the patients.xml file and create a patients.html file. The following
snippet shows the important pieces of this class:
import
javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
...
public void run(String xmlFile, String xslFile, String
outputFile)
throws FileNotFoundException,
TransformerConfigurationException, TransformerException {
InputStream xslInputStream = new
FileInputStream(xslFile);
Source xslSource = new StreamSource(xslInputStream);
TransformerFactory factory
= TransformerFactory.newInstance();
Transformer transformer
= factory.newTransformer(xslSource);
InputStream xmlInputStream = new
FileInputStream(xmlFile);
StreamSource in = new StreamSource(xmlInputStream);
StreamResult out = new StreamResult(outputFile);
transformer.transform(in, out);
Search WWH ::




Custom Search