I have a xml representation of object like OrderList (has list of) Orders and each order has a list of commodities.
I want to validate my commodities and if not valid I want to remove them from order. If all commodities are invalid then I remove the order from the orderlist.
I have been able to validate Orderlist
JAXBContext jaxbContext = JAXBContext.newInstance("com.jaxb");
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(new File(XSD));
JAXBSource source = new JAXBSource(jaxbContext, orderList);
Validator validator = schema.newValidator();
DataFeedErrorHandler handler = new DataFeedErrorHandler();
validator.setErrorHandler(handler);
validator.validate(source);
I am not able to find a way to validate commodities.
Something like
for(Order order: orderList){
for(Commodity commodity: order.getCommodity()){
if(!isCommodityValid(commodity)){
// mark for removal
}
}
}
Any help would be greatly appreciated.
TL;DR
You can do a dummy marshal and leverage the JAXB validation mechanisms rather than using the
javax.xml.validation
mechanisms directly.LEVERAGING
Marshaller.Listener
&ValidationEventHandler
(CommodityValidator)For this example we will leverage aspects of
Marshaller.Listener
andValidationEventHandler
to accomplish the use case.Marshal.Listener
- This will be called for each object being marshalled. We can use it to cache the instance ofOrder
that we may need to remove the instance ofCommodity
from.ValidationEventHandler
this will give us access to each problem occuring with validation during themarshal
operation. For each problem it will be passed aValidationEvent
. ThisValidationEvent
will hold aValidationEventLocator
from which we can get the object that had the problem being marshalled.DEMO CODE
The following code can be run to prove that everything works.
OUTPUT
Below is the output from running the demo code. Node how after the marshal operation the invalid commodity was removed.
XML SCHEMA (schema.xsd)
Below is the XML schema used for this example.
JAVA MODEL
Below is the object model I used for this example.
Orders
Order
Commodity