执行基本 XSLT 操作
您可以使用 XSLTExecutable 实例(使用 XFactory.prepareXSLT 方法创建的实例),执行 XSLT 变换。
关于此任务
可以使用 JAXP 源对象将 XSLT 样式表传递到 XFactory.prepareXSLT 方法。生成的 XSLTExecutable 实例对于线程是安全的,且可复用以变换多个输入文档。
过程
示例
以下是准备和执行已解释变换的基本示例。
// Create the factory
XFactory factory = XFactory.newInstance();
// Create a StreamSource for the stylesheet
StreamSource stylesheet = new StreamSource("simple.xsl");
// Create an XSLT executable for the stylesheet
XSLTExecutable executable = factory.prepareXSLT(stylesheet);
// Create the input source
Source input = new StreamSource("simple.xml");
// Create the result
Result result = new StreamResult(System.out);
// Execute the transformation
executable.execute(input, result);
以下是准备和执行已编译变换的基本示例。
// Create the factory
XFactory factory = XFactory.newInstance();
// Create a StreamSource for the stylesheet
StreamSource stylesheet = new StreamSource("simple.xsl");
// Create a new static context
XStaticContext staticContext = factory.newStaticContext();
// Enable the compiler
staticContext.setUseCompiler(true);
// Create an XSLT executable for the stylesheet
XSLTExecutable executable = factory.prepareXSLT(stylesheet, staticContext);
// Create the input source
Source input = new StreamSource("simple.xml");
// Create the result
Result result = new StreamResult(System.out);
// Execute the transformation
executable.execute(input, result);
以下是创建标识变换的基本示例。
// Create the factory
XFactory factory = XFactory.newInstance();
// Create the item factory
XItemFactory itemFactory = factory.getItemFactory();
// Create the input source
Source input = new StreamSource("simple.xml");
// Create the XItemView object from the input source
XItemView item = itemFactory.item(input);
// Create an XOutputParameters object
XOutputParameters params = factory.newOutputParameters();
// Set parameters
params.setMethod("xml");
params.setEncoding("UTF-8");
params.setIndent(true);
// Create the result
Result result = new StreamResult(System.out);
// Serialize to the result
item.exportItem(result, params);
以下是创建模式感知变换的基本示例。
// Create the factory
XFactory factory = XFactory.newInstance();
// Enable validation
factory.setValidating(true);
// Create the schema source
StreamSource schema = new StreamSource("schema.xsd");
// Register the schema
factory.registerSchema(schema);
// Create the stylesheet source
StreamSource stylesheet = new StreamSource("schema.xsl");
// Create an XSLT executable for the stylesheet
XSLTExecutable executable = factory.prepareXSLT(stylesheet);
// Create the input source
StreamSource input = new StreamSource("schema.xml");
// Create the result
StreamResult result = new StreamResult(System.out);
// Execute the transformation
executable.execute(input, result);