package february;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class Xml2Html {
private static String xsl = "<?xml version='1.0'?>" +
"<xsl:stylesheet xmlns:xsl='
http://www.w3.org/1999/XSL/Transform' version='1.0'>" +
"<xsl:template match='/'>" +
"<ul>" +
"<xsl:apply-templates/>" +
"</ul>" +
"</xsl:template>" +
"<xsl:template match='nyhed'>" +
"<li><a>" +
"<xsl:attribute name='href'><xsl:value-of select='link'/></xsl:attribute>" +
"<xsl:value-of select='overskrift'/>" +
"</a></li>" +
"</xsl:template>" +
"</xsl:stylesheet>";
public static String transform(String xml) throws Exception {
StringWriter sw = new StringWriter();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer(new StreamSource(new StringReader(xsl)));
t.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
t.setOutputProperty(OutputKeys.METHOD, "html");
t.transform(new StreamSource(new StringReader(xml)), new StreamResult(sw));
return sw.toString();
}
public static String load(String urlstr) throws Exception {
URL url = new URL(urlstr);
StringBuffer sb = new StringBuffer("");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while((line = in.readLine()) != null) {
sb.append(line);
sb.append('\n');
}
return sb.toString();
}
public static void main(String[] args) throws Exception {
String xml = load("
http://www.haandbold.com/xml/xml_nyheder.xml");
System.out.println(xml);
String html = transform(xml);
System.out.println(html);
}
}