[英]Catching exceptions with Xalan xslt
I have the folowwing XSLT
based on Xalan
: 我有基于
Xalan
以下XSLT
:
TransformerFactory factory = TransformerFactory.newInstance();
XalanErrorListener listener = new XalanErrorListener();
factory.setErrorListener(listener);
// Create transformer
StreamSource config = new StreamSource(xslPath);
Transformer transformer = factory.newTransformer(config);
// Create input / ouput
StreamSource source = new StreamSource(inputPath);
StreamResult result = new StreamResult(outputPath);
// Transform
transformer.transform(source, result);
My XalanErrorListener
simply overrides error
, fatalError
and warning
methods from the javax.xml.transform.ErrorListener
class and logs the exception: 我的
XalanErrorListener
只是从javax.xml.transform.ErrorListener
类重写error
, fatalError
和warning
方法,并记录异常:
public final class XalanErrorListener implements ErrorListener {
static final Logger LOGGER = LoggerFactory.getLogger(XalanErrorListener.class);
@Override
public void error(TransformerException exception) throws TransformerException {
LOGGER.error(exception);
}
@Override
public void fatalError(TransformerException exception) throws TransformerException {
LOGGER.error(exception);
}
@Override
public void warning(TransformerException exception) throws TransformerException {
LOGGER.warn(exception);
}
}
Yet, when executing on a badly encoded file, I get the following message in the console: 但是,当在编码错误的文件上执行时,我在控制台中收到以下消息:
(Location of error unknown)
com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException:
Invalid byte 2 of 2-byte UTF-8 sequence.
The program executes normally: no exception is thrown or logged and the generated file is empty! 程序正常执行:不会引发或记录异常,并且生成的文件为空!
How can I catch the exception to handle it the way I want? 如何捕获异常以所需方式处理它?
The ErrorListener you supply to Xalan catches transformation errors, but it does not catch XML parsing errors. 您提供给Xalan的ErrorListener会捕获转换错误,但不会捕获XML解析错误。 For that you need to supply an ErrorHandler to the Xerces parser.
为此,您需要向Xerces解析器提供一个ErrorHandler。
The problem came from the fact that the ErrorListener
needed to be set to the Transformer
and not the TransformerFactory
: 问题来自以下事实:需要将
ErrorListener
设置为Transformer
而不是TransformerFactory
:
Transformer transformer = factory.newTransformer(config);
transformer.setErrorListener(listener);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.