注册模式解析器
可以实现 XSchemaResolver 接口,且向 XFactory 注册实现以覆盖缺省模式解析行为。这包括使用 registerSchema 方法解析向 XFactory 注册的模式的导入,以及使用 xsl:import-schema 声明解析在 XSLT 样式表中导入的模式。
关于此任务
解析模式中导入的缺省行为是使用模式的基本 URI 解析已导入模式的位置。XSLT 模式导入的缺省行为是使用 xsl:import-schema 声明的基本 URI,以解析声明中指定的位置。
过程
在 XFactory 类上使用 setSchemaResolver 方法,以注册模式解析器。
getSchema 方法会返回 java.util.List 接口的实例。这是因为特定名称空间的模式组件定义可跨多个不同模式文档进行拆分。您可以使用 getSchema 方法,返回与所有指定位置提示关联的特定目标名称空间的所有模式文档。
示例
以下是使用模式解析器的基本示例。
XFactory factory = XFactory.newInstance();
// Set validating to true.
factory.setValidating(true);
// Create the schema resolver and register it with the factory.
factory.setSchemaResolver(new ASchemaResolver(replacementBase));
// Prepare the stylesheet.
XSLTExecutable executable = factory.prepareXSLT(new StreamSource(stylesheetFile));
// Execute the transformation.
Source source = new StreamSource(inputFile);
Result result = new StreamResult(System.out);
executable.execute(source, result);
以下是 XSchemaResolver 实现的基本示例。
class ASchemaResolver implements XSchemaResolver
{
String _replacementBase;
public ASchemaResolver(String replacementBase)
{
_replacementBase=replacementBase;
}
// Resolve URI, returning the Source that URI represents.
// Implements the "rebase:" pseudo-scheme.
public List<? extends Source> getSchema(String namespace, List<String> locations, String baseURI) {
String rebasePrefix="rebase:";
List<StreamSource> list = new ArrayList<StreamSource>();
for (int i = 0; i < locations.size(); i++) {
String href = locations.get(i);
String base = baseURI;
if(href.startsWith(rebasePrefix)) {
href=href.substring(rebasePrefix.length());
base=_replacementBase;
}
java.net.URI uri;
StreamSource source=null;
try {
// Get base URI object
uri = new java.net.URI(base);
// Resolved relative reference against base URI
URI resolvedURI = uri.resolve(href);
// Try to read...
source = new StreamSource(resolvedURI.toString());
} catch (java.net.URISyntaxException use) {
throw new RuntimeException(use);
}
list.add(source);
}
return list;
}
}