[英]How to apply xsl to xml in Java
這是被問過很多次的問題,但我並沒有真正找到我正在尋找的東西。 我通常不用Java編寫代碼,而是用C#編寫代碼,所以我對Java類等不熟悉。
題
我需要創建一個需要2個參數的方法。 1.一個字符串參數(xml - 所以需要轉換為某個xml類)2。帶有xsl文件路徑位置的字符串參數
問題是我正在制作一個工廠類,必須將xml從webservice轉換為我的系統可以理解的xml。 我需要一個很好的解決方案。 ws上的每個方法都有一個xsl文件 - 請求(將我的xml轉換為ws理解的東西)和響應(轉換為我的系統理解的東西)。
您可能會發現Java Almanac是一個有用的資源。
特別是使用XSL轉換XML文件的典型程序 。 從頁面復制的示例(因為它一直在消失)
import java.io.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
public class BasicXsl {
// This method applies the xslFilename to inFilename and writes
// the output to outFilename.
public static void xsl(String inFilename, String outFilename, String xslFilename) {
try {
// Create transformer factory
TransformerFactory factory = TransformerFactory.newInstance();
// Use the factory to create a template containing the xsl file
Templates template = factory.newTemplates(new StreamSource(
new FileInputStream(xslFilename)));
// Use the template to create a transformer
Transformer xformer = template.newTransformer();
// Prepare the input and output files
Source source = new StreamSource(new FileInputStream(inFilename));
Result result = new StreamResult(new FileOutputStream(outFilename));
// Apply the xsl file to the source file and write the result
// to the output file
xformer.transform(source, result);
} catch (FileNotFoundException e) {
} catch (TransformerConfigurationException e) {
// An error occurred in the XSL file
} catch (TransformerException e) {
// An error occurred while applying the XSL file
// Get location of error in input file
SourceLocator locator = e.getLocator();
int col = locator.getColumnNumber();
int line = locator.getLineNumber();
String publicId = locator.getPublicId();
String systemId = locator.getSystemId();
}
}
}
樣本輸入:
<?xml version="1.0" encoding="UTF-8"?>
<map>
<entry key="key1" value="value1" />
<entry key="key2" />
</map>
示例XSLT程序:
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html" indent="yes"/>
<xsl:template match="map">
<HTML>
<HEAD>
<TITLE>Map</TITLE>
</HEAD>
<BODY>
<xsl:apply-templates/>
</BODY>
</HTML>
</xsl:template>
<xsl:template match="entry">
<xsl:value-of select="@key"/>=<xsl:value-of select="@value"/>
<br></br>
</xsl:template>
</xsl:stylesheet>
運行該示例生成的HTML是:
<HTML>
<HEAD>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>Map</TITLE>
</HEAD>
<BODY>
key1=value1<br>
key2=<br>
</BODY>
</HTML>
谷歌的“JAXP教程” - 有很多可用的資源。
雖然如果你想使用XSLT 2.0(相信我,你呢!),你將使用Saxon,Saxon提供JAXP和它自己的API(稱為s9api),它可以幫助你利用XSLT中的所有新功能2.0。
看看http://www.rgagnon.com/javadetails/java-0407.html ,希望能回答你的問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.