Java Reference
In-Depth Information
t.setOutputProperty(OutputKeys.ENCODING, "iso-8859-1");
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-
amount", "3");
Source source = new DOMSource(doc);
Result result = new StreamResult(System.out);
t.transform(source, result);
After creating a transformer factory and obtaining a transformer from this factory,
four output properties are specified to influence the transformation. Out-
putKeys.METHOD specifies that the result tree will be written out as XML, Out-
putKeys.ENCODING specifiesthat ISO-8859-1 willbethevalueoftheXMLde-
claration's encoding attribute,and OutputKeys.INDENT specifiesthatthetrans-
former can output additional whitespace.
TheadditionalwhitespaceisusedtooutputtheXMLacrossmultiplelinesinsteadof
onasingleline.Becauseitwouldbenicetoindicatethenumberofspacesforindenting
lines of XML, and because this information cannot be specified via an OutputKeys
property, the nonstandard "{http://xml.apache.org/xslt}indent-
amount" property(propertykeysbeginwithbrace-delimitedURIs)isusedtospecify
anappropriatevalue(suchas3spaces).It'sokaytospecifythispropertyinthisexample
becauseJava'sdefaultXSLTimplementationisbasedonApache'sXSLTimplementa-
tion.
Aftersettingproperties,asource(theDOMdocumenttree)andaresult(thestandard
outputstream)areobtained,and transform() iscalledtotransformthesourcetothe
result.
AlthoughthisexampleshowsyouhowtooutputaDOMtree,andalsohowtospecify
an encoding valuefortheXMLdeclarationoftheresultingXMLdocument,theex-
ample doesn't really demonstrate the power of XSLT because (apart from setting the
encoding attribute value) it performs an identity transformation. A more interesting
example would take advantage of a stylesheet.
Considerascenariowhereyouwanttoconvert Listing10-1 'srecipedocumenttoan
HTMLdocumentforpresentationviaawebbrowser. Listing10-28 presentsastylesheet
that a transformer can use to perform the conversion.
Listing 10-28. An XSLT stylesheet for converting a recipe document to an HTML document
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
Search WWH ::




Custom Search