Domanda

I have the folowwing XSLT based on Xalan:

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:

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?

È stato utile?

Soluzione 2

The problem came from the fact that the ErrorListener needed to be set to the Transformer and not the TransformerFactory:

Transformer transformer = factory.newTransformer(config);
transformer.setErrorListener(listener);

Altri suggerimenti

The ErrorListener you supply to Xalan catches transformation errors, but it does not catch XML parsing errors. For that you need to supply an ErrorHandler to the Xerces parser.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top