jaxb validation event locator - row and col number of validation error
When doing JAXB marshalling I am collecting validation error and also want to get the line number and column number where the error occurs. I keep getting columnNumber=-1 and lineNumber=-1 for all the errors. Is there anything that I am forgetting?
Code sample:
Marshaller marshaler = jaxbCtx.createMarshaller();
marshaler.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
ValidationErrorCollector errorCollector = new ValidationErrorCollector();
marshaler.setEventHandler(errorCollector);
marshaler.setSchema(getSchema());
marshaler.setProperty("com.sun.xml.bind.namespacePrefixMapper", new MyNamespacePrefixMapper());
JAXBElement<RootObject> jaxbElement开发者_如何学运维 = new JAXBElement<RootObject>(ROOT_QNAME, RootObject.class, (RootObject) rootObject);
marshaler.marshal(jaxbElement, new StringWriter());
for (ValidationEvent validationEvent : errorCollector.getValidationEvents()) {
validationEvent.getLocator().getColumnNumber(); // returns -1
validationEvent.getLocator().getLineNumber(); // returns -1
...
public class ValidationErrorCollector implements ValidationEventHandler {
/** List of validation events (with validation errors). */
private List<ValidationEvent> validationEvents = new ArrayList<ValidationEvent>();
@Override
public boolean handleEvent(ValidationEvent validationEvent) {
// record the validation error
validationEvents.add(validationEvent);
// let validation continue
return true;
}
That is the expected behavior. When you're marshaling the source of the error comes from the object being marshalled. The object can also be found through the event.
For more information see:
- http://bdoughan.blogspot.com/2010/12/jaxb-and-marshalunmarshal-schema.html
Which column and line number (in which file) do you expect to retrieve? I think this is by design. Line number and column number are for ValidationEvent which happen on unmarshalling. In such a case you get the position of the problem in the XML file to be unmarshalled.
But in your case you are trying to marshall an object - hence there is no XML file and therefore you don't get a column or a line number.
精彩评论