I am trying to transform an xml file with xsl stylesheet into html.
this is the java
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(new StreamSource(classLoader.getResourceAsStream("driving.xsl")));
StreamResult drivingHtml = new StreamResult(new StringWriter());
transformer.transform(new StreamSource(classLoader.getResourceAsStream("driving.xml")), drivingHtml);
System.out.println(drivingHtml.getWriter().toString());
this is some of the xml:
<?xml version="1.0" encoding="UTF-8"?>
<user xmlns="http://notreal.org/ns1" xmlns:poi="http://notreal2.org/ns2">
<address type="primary">
<street>1031 Court St.</street>
<city>Monhegan, NY</city>
</address>
<address type="secondary">
<street> Elm St.</street>
</address>
this is the xsl:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<head>
<title>User</title>
</head>
<body>
<p>Detailed Addresses</p>
<xsl:apply-templates select="/user/address"/>
</body>
</html>
</xsl:template>
<xsl:template match="address">
<table>
<th>Primary</th>
<th>Secondary</th>
<tr>
<td>
<xsl:value-of select="address" />
开发者_如何学C </td>
</tr>
</table>
</xsl:template>
</xsl:stylesheet>
when i run that, i get the html from the root template match, but nothing from the template matching address. i've tried other variations of templates, and instead of getting at least the basic html, i just get the entire contents of xml file ouputted.
Check your namespace or or modify your XML to something like the following one to add a namespace-prefix:
<?xml version="1.0" encoding="UTF-8"?>
<user xmlns:a="http://notreal.org/ns1" xmlns:poi="http://notreal2.org/ns2">
<address type="primary">
<street>1031 Court St.</street>
<city>Monhegan, NY</city>
</address>
<address type="secondary">
<street> Elm St.</street>
</address>
</user>
Looks like a namespace issue. The address
element in the source has the namespace http://notreal.org/ns1
, but your XSLT doesn't reference that namespace at all.
Try including the xmlns="http://notreal.org/ns1"
in your xslt.
精彩评论