2009年1月5日

XML transform using XSLT

W3C XSL Transformations (XSLT)

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;

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 {
// XSL
StringBuilder xslSb = new StringBuilder();
xslSb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
.append("<xsl:stylesheet ")
.append(" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"")
.append(" version=\"1.0\">")
.append("<xsl:template match=\"/\">")
.append("<html><head><title>XSLT</title></head><body>")
.append("<table border=\"1\">")
.append("<tr><th>Name</th><th>Birthday</th></tr>")
.append("<xsl:for-each select=\"/root/user\">")
.append("<tr>")
.append("<td><xsl:value-of select=\"name\"/></td>")
.append("<td><xsl:value-of select=\"birthday\"/></td>")
.append("</tr>")
.append("</xsl:for-each>")
.append("</table>")
.append("</body></html>")
.append("</xsl:template>")
.append("</xsl:stylesheet>");
InputStream xslIs = new ByteArrayInputStream(xslSb.toString().getBytes("UTF-8"));
StreamSource xsl = new StreamSource(xslIs);

// XML
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
.append("<root>")
.append("<user>")
.append("<name>Solnone</name>")
.append("<birthday>1900-01-01</birthday>")
.append("</user>")
.append("<user>")
.append("<name>John</name>")
.append("<birthday>1912-02-02</birthday>")
.append("</user>")
.append("</root>");
InputStream xmlIs = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
StreamSource xml = new StreamSource(xmlIs);

// Output
StringWriter sw = new StringWriter();
StreamResult outputTarget = new StreamResult(sw);

// transform
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(xsl);
transformer.transform(xml, outputTarget);

xmlIs.close();
xslIs.close();
System.out.println(sw.toString());
}
}

沒有留言:

網誌存檔