Java/XML/Transform — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 07:16, 1 июня 2010
Содержание
- 1 Applying XSLT Stylesheets
- 2 A Program That Performs XML Transformations
- 3 Catch TransformerException
- 4 Create an XML file and attach an XSL
- 5 Formatting an XML file using Transformer
- 6 Processing XML Documents Partially
- 7 Set the TransformerFactory system property to generate and use translets
- 8 Transformer with parameters
- 9 Transforming an XML File with XSL into a DOM Document
- 10 Transforming DOM Node to HTML with JAXP
- 11 Use the transform.TransformerFactory plugability in the JAXP API
- 12 XML input, output and transform utilities
- 13 XML transformation
- 14 XSLT I18N
Applying XSLT Stylesheets
import java.io.File;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class Main {
public static void main(String[] args) throws Exception{
StreamSource xmlFile = new StreamSource(new File(args[0]));
StreamSource xsltFile = new StreamSource(new File(args[1]));
TransformerFactory xsltFactory = TransformerFactory.newInstance();
Transformer transformer = xsltFactory.newTransformer(xsltFile);
StreamResult resultStream = new StreamResult(System.out);
transformer.transform(xmlFile, resultStream);
}
}
A Program That Performs XML Transformations
import javax.xml.transform.ErrorListener;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class SimpleXMLTransform {
static public void main(String[] arg) {
if(arg.length != 3) {
System.err.println("Usage: SimpleXMLTransform " +
"<input.xml> <input.xsl> <output>");
System.exit(1);
}
String inXML = arg[0];
String inXSL = arg[1];
String outTXT = arg[2];
SimpleXMLTransform st = new SimpleXMLTransform();
try {
st.transform(inXML,inXSL,outTXT);
} catch(TransformerConfigurationException e) {
System.err.println("Invalid factory configuration");
System.err.println(e);
} catch(TransformerException e) {
System.err.println("Error during transformation");
System.err.println(e);
}
}
public void transform(String inXML,String inXSL,String outTXT)
throws TransformerConfigurationException,
TransformerException {
TransformerFactory factory = TransformerFactory.newInstance();
StreamSource xslStream = new StreamSource(inXSL);
Transformer transformer = factory.newTransformer(xslStream);
transformer.setErrorListener(new MyErrorListener());
StreamSource in = new StreamSource(inXML);
StreamResult out = new StreamResult(outTXT);
transformer.transform(in,out);
}
}
class MyErrorListener implements ErrorListener {
public void warning(TransformerException e)
throws TransformerException {
show("Warning",e);
throw(e);
}
public void error(TransformerException e)
throws TransformerException {
show("Error",e);
throw(e);
}
public void fatalError(TransformerException e)
throws TransformerException {
show("Fatal Error",e);
throw(e);
}
private void show(String type,TransformerException e) {
System.out.println(type + ": " + e.getMessage());
if(e.getLocationAsString() != null)
System.out.println(e.getLocationAsString());
}
}
/*
The Basic Form of an XSL Stylesheet Document
<?xml version="1.0"?>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="/">
Ignore the input and output this line.
</xsl:template>
</xsl:stylesheet>
<!-- XML document-->
<folks>
<person>
<name>Jack Lee</name>
<phone>555-3333</phone>
</person>
</folks>
*/
Catch TransformerException
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.SourceLocator;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class Main {
public static void xsl(String inFilename, String outFilename, String xslFilename) {
try {
TransformerFactory factory = TransformerFactory.newInstance();
Templates template = factory.newTemplates(new StreamSource(new FileInputStream(xslFilename)));
Transformer xformer = template.newTransformer();
Source source = new StreamSource(new FileInputStream(inFilename));
Result result = new StreamResult(new FileOutputStream(outFilename));
xformer.transform(source, result);
} catch (FileNotFoundException e) {
} catch (TransformerConfigurationException e) {
} catch (TransformerException e) {
SourceLocator locator = e.getLocator();
int col = locator.getColumnNumber();
int line = locator.getLineNumber();
String publicId = locator.getPublicId();
String systemId = locator.getSystemId();
}
}
}
Create an XML file and attach an XSL
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class Main {
public static void main(String args[]) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
DOMImplementation impl = builder.getDOMImplementation();
Document xmldoc = impl.createDocument(null, "XMLDoc", null);
Element root = xmldoc.getDocumentElement();
Element e0 = xmldoc.createElement("Doc");
Element e1 = xmldoc.createElement("TITLE");
Node n1 = xmldoc.createTextNode("Java");
e1.appendChild(n1);
Element e2 = xmldoc.createElement("data");
Node n2 = xmldoc.createTextNode("text node");
e2.appendChild(n2);
e0.appendChild(e1);
e0.appendChild(e2);
root.appendChild(e0);
StreamResult out = new StreamResult("howto.xml");
DOMSource domSource = new DOMSource(xmldoc);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(domSource, out);
}
}
Formatting an XML file using Transformer
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
public class Main {
public static void main(String[] argv) throws Exception {
}
static void formatXMLFile(String file) throws Exception{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new InputStreamReader(new FileInputStream(
file))));
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.setOutputProperty(OutputKeys.METHOD, "xml");
xformer.setOutputProperty(OutputKeys.INDENT, "yes");
xformer.setOutputProperty("b;http://xml.apache.org/xsltd;indent-amount", "4");
xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
Source source = new DOMSource(document);
Result result = new StreamResult(new File(file));
xformer.transform(source, result);
}
}
Processing XML Documents Partially
import java.io.FileInputStream;
import java.io.OutputStreamWriter;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.traversal.NodeIterator;
import org.xml.sax.InputSource;
import com.sun.org.apache.xpath.internal.CachedXPathAPI;
public class MainClass {
public static void main(String[] args) throws Exception {
InputSource in = new InputSource(new FileInputStream("y.xml"));
DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
dfactory.setNamespaceAware(true);
Document doc = dfactory.newDocumentBuilder().parse(in);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
CachedXPathAPI path = new CachedXPathAPI();
NodeIterator nl = path.selectNodeIterator(doc, "\\abc\\");
Node n;
while ((n = nl.nextNode()) != null)
transformer.transform(new DOMSource(n), new StreamResult(new OutputStreamWriter(System.out)));
}
}
Set the TransformerFactory system property to generate and use translets
import java.io.FileOutputStream;
import java.util.Properties;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class MainClass {
public static void main(String argv[]) throws Exception {
Properties props = System.getProperties();
props.put("javax.xml.transform.TransformerFactory",
"org.apache.xalan.xsltc.trax.TransformerFactoryImpl");
System.setProperties(props);
TransformerFactory tFactory = TransformerFactory.newInstance();
Templates translet = tFactory.newTemplates(new StreamSource(
"OrderProcessing.xslt"));
Transformer transformer = translet.newTransformer();
transformer.transform(new StreamSource("CustomerOrders.xml"),
new StreamResult(new FileOutputStream("SortedOrders.html")));
transformer.transform(new StreamSource("CustomerOrders1.xml"),
new StreamResult(new FileOutputStream("SortedOrders1.html")));
}
}
Transformer with parameters
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.xml.sax.XMLReader;
public class XMLTransform {
public static void main(String[] args) throws Exception {
System.setProperty("javax.xml.transform.TransformerFactory",
"net.sf.saxon.TransformerFactoryImpl");
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
XMLReader reader = parser.getXMLReader();
TransformerFactory factory = TransformerFactory.newInstance();
System.out.println(factory);
Transformer transformer = factory.newTransformer(new StreamSource("./xsl/books-sql.xsl"));
transformer.setParameter("user", "root");
transformer.setParameter("password", "123456");
transformer.transform(new StreamSource("./xml/books.xml"), new StreamResult(System.out));
}
}
Transforming an XML File with XSL into a DOM Document
import java.io.FileInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
public class Main {
public static void main(String[] argv) throws Exception {
TransformerFactory factory = TransformerFactory.newInstance();
Templates template = factory.newTemplates(new StreamSource(new FileInputStream("xsl.xlt")));
Transformer xformer = template.newTransformer();
Source source = new StreamSource(new FileInputStream("in.xml"));
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.newDocument();
Result result = new DOMResult(doc);
xformer.transform(source, result);
}
}
Transforming DOM Node to HTML with JAXP
import java.io.File;
import java.io.FileOutputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class MainClass {
public static void main(String args[]) throws Exception {
TransformerFactory factory = TransformerFactory.newInstance();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
DOMSource stylesheet = new DOMSource(db.parse(new File("y.xml")));
StreamSource xmlDoc = new StreamSource(args[0]);
StreamResult result = new StreamResult(new FileOutputStream(args[2]));
Transformer transFormer = factory.newTransformer(stylesheet);
transFormer.transform(xmlDoc, result);
}
}
Use the transform.TransformerFactory plugability in the JAXP API
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class MainClass {
public static void main(String[] args) throws TransformerException,
TransformerConfigurationException, FileNotFoundException, IOException {
if (args.length != 3) {
System.out.println("Usage: java jaxpTransform inXML inXSLT outFile");
System.exit(0);
}
FileOutputStream outstream = new FileOutputStream(args[2]);
TransformerFactory tfactory = TransformerFactory.newInstance();
StreamSource insource = new StreamSource(args[0]);
StreamSource inxsl = new StreamSource(args[1]);
StreamResult sresult = new StreamResult(outstream);
Transformer transformer = tfactory.newTransformer(inxsl);
transformer.transform(insource, sresult);
}
}
XML input, output and transform utilities
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.WeakHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public final class XMLUtils {
private static final Map<ClassLoader, DocumentBuilderFactory> DOCUMENT_BUILDER_FACTORIES
= Collections.synchronizedMap(new WeakHashMap<ClassLoader, DocumentBuilderFactory>());
private static final Map<ClassLoader, TransformerFactory> TRANSFORMER_FACTORIES
= Collections.synchronizedMap(new WeakHashMap<ClassLoader, TransformerFactory>());
private XMLUtils() {
}
private static TransformerFactory getTransformerFactory() {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
if (loader == null) {
loader = XMLUtils.class.getClassLoader();
}
if (loader == null) {
return TransformerFactory.newInstance();
}
TransformerFactory factory = TRANSFORMER_FACTORIES.get(loader);
if (factory == null) {
factory = TransformerFactory.newInstance();
TRANSFORMER_FACTORIES.put(loader, factory);
}
return factory;
}
private static DocumentBuilderFactory getDocumentBuilderFactory() {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
if (loader == null) {
loader = XMLUtils.class.getClassLoader();
}
if (loader == null) {
return DocumentBuilderFactory.newInstance();
}
DocumentBuilderFactory factory = DOCUMENT_BUILDER_FACTORIES.get(loader);
if (factory == null) {
factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DOCUMENT_BUILDER_FACTORIES.put(loader, factory);
}
return factory;
}
public static Transformer newTransformer() throws TransformerConfigurationException {
return getTransformerFactory().newTransformer();
}
public static DocumentBuilder getParser() throws ParserConfigurationException {
return getDocumentBuilderFactory().newDocumentBuilder();
}
public static Document parse(InputSource is) throws ParserConfigurationException, SAXException,
IOException {
return getParser().parse(is.getSystemId());
}
public static Document parse(File is) throws ParserConfigurationException, SAXException,
IOException {
return getParser().parse(is);
}
public static Document parse(InputStream in) throws ParserConfigurationException, SAXException,
IOException {
return getParser().parse(in);
}
public static Document parse(String in) throws ParserConfigurationException, SAXException, IOException {
return parse(in.getBytes());
}
public static Document parse(byte[] in) throws ParserConfigurationException, SAXException, IOException {
return getParser().parse(new ByteArrayInputStream(in));
}
public static Document newDocument() throws ParserConfigurationException {
return getParser().newDocument();
}
public static void writeTo(Node node, OutputStream os) {
writeTo(new DOMSource(node), os);
}
public static void writeTo(Node node, OutputStream os, int indent) {
writeTo(new DOMSource(node), os, indent);
}
public static void writeTo(Source src, OutputStream os) {
writeTo(src, os, -1);
}
public static void writeTo(Source src, OutputStream os, int indent) {
String enc = null;
if (src instanceof DOMSource
&& ((DOMSource)src).getNode() instanceof Document) {
enc = ((Document)((DOMSource)src).getNode()).getXmlEncoding();
}
writeTo(src, os, indent, enc, "no");
}
public static void writeTo(Source src,
OutputStream os,
int indent,
String charset,
String omitXmlDecl) {
Transformer it;
try {
//charset = "utf-8";
it = newTransformer();
it.setOutputProperty(OutputKeys.METHOD, "xml");
if (indent > -1) {
it.setOutputProperty(OutputKeys.INDENT, "yes");
it.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",
Integer.toString(indent));
}
it.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omitXmlDecl);
it.setOutputProperty(OutputKeys.ENCODING, charset);
it.transform(src, new StreamResult(os));
} catch (TransformerException e) {
throw new RuntimeException("Failed to configure TRaX", e);
}
}
public static String toString(Source source) throws TransformerException, IOException {
return toString(source, null);
}
public static String toString(Source source, Properties props) throws TransformerException, IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
StreamResult sr = new StreamResult(bos);
Transformer trans = newTransformer();
if (props == null) {
props = new Properties();
props.put(OutputKeys.OMIT_XML_DECLARATION, "yes");
}
trans.setOutputProperties(props);
trans.transform(source, sr);
bos.close();
return bos.toString();
}
public static String toString(Node node, int indent) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
writeTo(node, out, indent);
return out.toString();
}
public static String toString(Node node) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
writeTo(node, out);
return out.toString();
}
public static void printDOM(Node node) {
printDOM("", node);
}
public static void printDOM(String words, Node node) {
System.out.println(words);
System.out.println(toString(node));
}
public static Attr getAttribute(Element el, String attrName) {
return el.getAttributeNode(attrName);
}
public static void replaceAttribute(Element element, String attr, String value) {
if (element.hasAttribute(attr)) {
element.removeAttribute(attr);
}
element.setAttribute(attr, value);
}
public static QName getNamespace(Map<String, String> namespaces, String str, String defaultNamespace) {
String prefix = null;
String localName = null;
StringTokenizer tokenizer = new StringTokenizer(str, ":");
if (tokenizer.countTokens() == 2) {
prefix = tokenizer.nextToken();
localName = tokenizer.nextToken();
} else if (tokenizer.countTokens() == 1) {
localName = tokenizer.nextToken();
}
String namespceURI = defaultNamespace;
if (prefix != null) {
namespceURI = (String)namespaces.get(prefix);
}
return new QName(namespceURI, localName);
}
public static Element createElementNS(Node node, QName name) {
return createElementNS(node.getOwnerDocument(), name.getNamespaceURI(), name.getLocalPart());
}
public static Element createElementNS(Document root, QName name) {
return createElementNS(root, name.getNamespaceURI(), name.getLocalPart());
}
public static Element createElementNS(Document root, String namespaceURI, String qualifiedName) {
return root.createElementNS(namespaceURI, qualifiedName);
}
public static Text createTextNode(Document root, String data) {
return root.createTextNode(data);
}
public static Text createTextNode(Node node, String data) {
return createTextNode(node.getOwnerDocument(), data);
}
public static void removeContents(Node parent) {
Node node = parent.getFirstChild();
while (node != null) {
parent.removeChild(node);
node = node.getNextSibling();
}
}
public static InputStream getInputStream(Document doc) throws Exception {
DOMImplementationLS impl = null;
DOMImplementation docImpl = doc.getImplementation();
// Try to get the DOMImplementation from doc first before
// defaulting to the sun implementation.
if (docImpl != null && docImpl.hasFeature("LS", "3.0")) {
impl = (DOMImplementationLS)docImpl.getFeature("LS", "3.0");
} else {
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
impl = (DOMImplementationLS)registry.getDOMImplementation("LS");
if (impl == null) {
System.setProperty(DOMImplementationRegistry.PROPERTY,
"com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl");
registry = DOMImplementationRegistry.newInstance();
impl = (DOMImplementationLS)registry.getDOMImplementation("LS");
}
}
LSOutput output = impl.createLSOutput();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
output.setByteStream(byteArrayOutputStream);
LSSerializer writer = impl.createLSSerializer();
writer.write(doc, output);
byte[] buf = byteArrayOutputStream.toByteArray();
return new ByteArrayInputStream(buf);
}
public static QName getQName(String value, Node node) {
if (value == null) {
return null;
}
int index = value.indexOf(":");
if (index == -1) {
return new QName(value);
}
String prefix = value.substring(0, index);
String localName = value.substring(index + 1);
String ns = node.lookupNamespaceURI(prefix);
if (ns == null || localName == null) {
throw new RuntimeException("Invalid QName in mapping: " + value);
}
return new QName(ns, localName, prefix);
}
public static Node fromSource(Source src) throws Exception {
Transformer trans = TransformerFactory.newInstance().newTransformer();
DOMResult res = new DOMResult();
trans.transform(src, res);
return res.getNode();
}
}
XML transformation
/* phonebook.xml
<PHONEBOOK>
<PERSON>
<NAME>Joe Wang</NAME>
<EMAIL>joe@yourserver.ru</EMAIL>
<TELEPHONE>202-999-9999</TELEPHONE>
<WEB>www.jexp.ru</WEB>
</PERSON>
<PERSON>
<NAME>Karol</name>
<EMAIL>karol@yourserver.ru</EMAIL>
<TELEPHONE>306-999-9999</TELEPHONE>
<WEB>www.jexp.ru</WEB>
</PERSON>
<PERSON>
<NAME>Green</NAME>
<EMAIL>green@yourserver.ru</EMAIL>
<TELEPHONE>202-414-9999</TELEPHONE>
<WEB>www.jexp.ru</WEB>
</PERSON>
</PHONEBOOK>
<!-- directory.xsl -->
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<html>
<head>
<title>Directory</title>
</head>
<body>
<table border="1">
<tr>
<th>Name</th>
<th>Telephone</th>
<th>Email</th>
</tr>
<xsl:for-each select="PHONEBOOK/PERSON">
<xsl:sort/>
<tr>
<td><xsl:value-of select="NAME"/></td>
<td><xsl:value-of select="TELEPHONE"/></td>
<td><xsl:value-of select="EMAIL"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
*/
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class XMLTransform {
public static void main(String args[]) {
if (args.length != 2) {
System.err.println("Usage: java XMLTransform xmlfile.xml stylesheet.xsl");
System.exit(-1);
}
try {
StreamSource source = new StreamSource(args[0]);
StreamSource stylesource = new StreamSource(args[1]);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(stylesource);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
XSLT I18N
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="directory_es.xslt"?>
<directory>
<employee category="manager">
<name>Joe S</name>
<phone>4-1111</phone>
</employee>
<employee category="programmer">
<name>A B</name>
<phone>4-2222</phone>
</employee>
<employee category="programmer">
<name>C D</name>
<phone>4-3333</phone>
</employee>
</directory>
//directory_en.xslt
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="UTF-8"/>
<!-- Isolate locale-specific content -->
<xsl:variable name="lang.pageTitle" select=""Employee Directory""/>
<xsl:variable name="lang.nameHeading" select=""Name""/>
<xsl:variable name="lang.categoryHeading" select=""Category""/>
<xsl:variable name="lang.phoneHeading" select=""Phone""/>
<xsl:variable name="lang.manager" select=""Manager""/>
<xsl:variable name="lang.programmer" select=""Programmer""/>
<xsl:variable name="lang.other" select=""Other""/>
<xsl:template match="/">
<html>
<head>
<title><xsl:value-of select="$lang.pageTitle"/></title>
</head>
<body>
<h1><xsl:value-of select="$lang.pageTitle"/></h1>
<table cellpadding="4" cellspacing="0" border="1">
<tr>
<th><xsl:value-of select="$lang.nameHeading"/></th>
<th><xsl:value-of select="$lang.categoryHeading"/></th>
<th><xsl:value-of select="$lang.phoneHeading"/></th>
</tr>
<xsl:for-each select="directory/employee">
<tr>
<td>
<xsl:value-of select="name"/>
</td>
<td>
<xsl:choose>
<xsl:when test="@category="manager"">
<xsl:value-of select="$lang.manager"/>
</xsl:when>
<xsl:when test="@category="programmer"">
<xsl:value-of select="$lang.programmer"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$lang.other"/>
</xsl:otherwise>
</xsl:choose>
</td>
<td>
<xsl:value-of select="phone"/>
</td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
//directory_basic.xslt
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="UTF-8"/>
<xsl:template match="/">
<html>
<head>
<title>Employee Directory</title>
</head>
<body>
<h1>Employee Directory</h1>
<table cellpadding="4" cellspacing="0" border="1">
<tr>
<th>Name</th>
<th>Category</th>
<th>Phone</th>
</tr>
<xsl:for-each select="directory/employee">
<tr>
<td>
<xsl:value-of select="name"/>
</td>
<td>
<xsl:choose>
<xsl:when test="@category="manager"">
<xsl:text>Manager</xsl:text>
</xsl:when>
<xsl:when test="@category="programmer"">
<xsl:text>Programmer</xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:text>Other</xsl:text>
</xsl:otherwise>
</xsl:choose>
</td>
<td>
<xsl:value-of select="phone"/>
</td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
//directory_es.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:import href="directory_en.xslt"/>
<xsl:output method="html" encoding="UTF-8"/>
<!-- Isolate locale-specific content -->
<xsl:variable name="lang.pageTitle" select=""Empleado guia telefonica""/>
<xsl:variable name="lang.nameHeading" select=""Nombre""/>
<xsl:variable name="lang.categoryHeading" select=""Categoria""/>
<xsl:variable name="lang.phoneHeading" select=""Telefono""/>
<xsl:variable name="lang.manager" select=""Gerente""/>
<xsl:variable name="lang.programmer" select=""Programador""/>
<xsl:variable name="lang.other" select=""Otro""/>
</xsl:stylesheet>