我想使用javax.xml.transform.Transformer提供的setURIResolver回调函数。我已经实施了“解决方案”。功能但它没有被调用。
public class XSLMagic implements URIResolver {
public void DoXSLTransform(final File xslDoc, final File xmlDoc, final File resultDoc) {
// Create the factory...
TransformerFactory tf = TransformerFactory.newInstance();
// Create the transformer object from
Transformer tr = tf.newTransformer(new StreamSource(xslDoc));
tr.setURIResolver(this); // <--- THIS LINE doesn't seem to work.
tr.transform(new StreamSource(xmlDoc), new StreamResult(resultDoc));
}
@Override
public Source resolve(String href, String base) throws TransformerException {
System.out.print("resolve: " + href + " " + base + "\n");
return null;
}
}
我已经测试过它没有被输出消息调用,也是通过在函数上设置调试点然后单步执行来调用。
我做错了什么?
答案 0 :(得分:1)
在写这篇文章的时候找到答案......:)
在TransformerFactory上设置setURIResolver,而不是Transformer对象。
所以代码就是......
public class XSLMagic implements URIResolver {
public void DoXSLTransform(final File xslDoc, final File xmlDoc, final File resultDoc) {
// Create the factory...
TransformerFactory tf = TransformerFactory.newInstance();
tf.setURIResolver(this); // WORKS - Set the URIResolver to the factory instead, 'resolve' function now called as expected.
// Create the transformer object from
Transformer tr = tf.newTransformer(new StreamSource(xslDoc));
tr.transform(new StreamSource(xmlDoc), new StreamResult(resultDoc));
}
@Override
public Source resolve(String href, String base) throws TransformerException {
System.out.print("resolve: " + href + " " + base + "\n");
return null;
}
}