我們使用JAVA進行XML/XSLT轉換。XSLT轉換不適用於xsl:incldue
這裏我們使用下面的URL加載book.xlst。 http://example.company.com/xslt/book.xslt
book.xlst內部使用xsl:include標記引用另一個xslincludefile.xsl。
<?xml version='1.0'?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes"/>
<xsl:template match="/">
<xsl:for-each select="COLLECTION/BOOK">
<xsl:apply-templates select="TITLE"/>
<xsl:apply-templates select="AUTHOR"/>
<xsl:apply-templates select="PUBLISHER"/>
<BR/>
</xsl:for-each>
</xsl:template>
<xsl:template match="TITLE">
<DIV STYLE="color:blue">
Title: <xsl:value-of select="."/>
</DIV>
</xsl:template>
<xsl:include href="xslincludefile.xsl" />
</xsl:stylesheet>
當我們運行程序時,它無法加載內部xslincludefile.xsl(http://example.company.com/xslt/xslincludefile.xsl),因爲它試圖從本地文件系統加載(文件://),而不是從服務器(HTTP://)。
ERROR
致命錯誤: '文件 「文件:///PATH/xslincludefile.xsl」 找不到。'
Java代碼的
InputStream ins = null;
String xslPath = "http://example.company.com/xslt/book.xslt";
File file = new File(xslPath);
String xmlData = "<?xml version=\"1.0\"?><COLLECTION><BOOK><TITLE>Lover Birds</TITLE><AUTHOR>Cynthia Randall</AUTHOR><PUBLISHER>Lucerne Publishing</PUBLISHER></BOOK></COLLECTION>";
javax.xml.transform.Source xslSource = null;
StreamSource xmlSource = new StreamSource(xmlData);
PostMethod postMethod = new PostMethod(xslPath.toString());
postMethod.addRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
HttpClient httpClient = new HttpClient();
int status = httpClient.executeMethod(postMethod);
if (status == HttpStatus.SC_OK) {
ins = postMethod.getResponseBodyAsStream();
xslSource = new StreamSource(ins);
URL url = new URL(xslPath);
TransformerFactory tFactory = TransformerFactory.newInstance();
FileOutputStream fos = new FileOutputStream("out.xml");
Transformer transformer = tFactory.newTransformer(xslSource);
transformer.transform(xmlSource, new javax.xml.transform.stream.StreamResult(fos));
}
難道我們做錯了什麼? 我們如何加載包含服務器上其他xslt的xslt?