Reputation: 303
During XML validation against an XSD file using JAXB I get JAXBExceptions
in case of invalid XML files. I get the message of the exceptions by calling event.getMessage()
. The resulting string is in german language.
I'm using JAXB 2.2. with java 8 on a german system.
What determines the language for the JAXB exception messages and how can I change it to english?
Here's the code:
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
try {
Schema schema = schemaFactory.newSchema();
JAXBContext jaxbContext = JAXBContext.newInstance("myPackage");
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
unmarshaller.setEventHandler(new XMLValidationEventHandler());
unmarshaller.setSchema(schema);
myClass = (myClass) unmarshaller.unmarshal(new File("myFile.xml"));
} catch (SAXException saxE) {
System.out.println("SAX-Exception during creation of Schema object!");
saxE.printStackTrace();
} catch (JAXBException e) {}
And this is the Event-Handler:
public class XMLValidationEventHandler implements ValidationEventHandler {
@Override
public boolean handleEvent(ValidationEvent event) {
System.out.println("XML validation failure in line "
+ event.getLocator().getLineNumber()
+ ", column " + event.getLocator().getColumnNumber()
+ ": " + event.getMessage());
return true;
}
Here is an example of the output of the event handler:
XML validation failure in line 8, column 48: cvc-maxInclusive-valid: Wert "10000" ist nicht Facet-gültig in Bezug auf maxInclusive "8.0E3" für Typ "Type". XML validation failure in line 17, column 64: Ungültiger Wert 250 für Feld Day. XML validation failure in line 17, column 64: cvc-datatype-valid.1.2.1: "2014-02-2501:00:00Z" ist kein gültiger Wert für "dateTime".
Upvotes: 13
Views: 3756
Reputation: 4206
You should use a validator to validate, not unmarshaller. You can change its locale like this:
import javax.xml.validation.Validator;
import com.sun.org.apache.xerces.internal.impl.XMLErrorReporter;
import org.xml.sax.ErrorHandler;
Validator validator = schema.newValidator();
ErrorHandler errorHandler = new YourErrorHandler();
validator.setErrorHandler(errorHandler);
XMLErrorReporter xmlErrorReporter = (XMLErrorReporter) validator
.getProperty("http://apache.org/xml/properties/internal/error-reporter");
xmlErrorReporter.setLocale(new Locale("ru", "RU"));
Though with Java9+ you'd need to export the com.sun.org.apache.xerces.internal.impl
package from the java.xml
module via compiler option. See this answer for more details.
Upvotes: 0
Reputation: 303
OK, I found out that the language used for the JAXB event messages is determined by the java system property user.language
. The default language is therefore dependent on the system it runs on.
I changed the run configuration of my java program by adding -Duser.language=en
. This changed the language of the JAXB event messages to english.
Upvotes: 7