is it possible to check a value in a java object with some rules in a xml schéma ?
For exemple, I have a String txt = "blablabla"
, and I should verify if it's ok for <xs:element name="foo" type="string32"/>
, with s开发者_运维技巧tring32 a restriction to 32 caract. length max.
Is it possible ? If it's not possible with xml schema and jaxb, is there other schema langage which is possible ?
Thanks.
You could do the following:
import java.io.File;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.util.JAXBSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
public class Demo {
public static void main(String[] args) throws Exception {
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(new File("customer.xsd"));
JAXBContext jc = JAXBContext.newInstance(Customer.class);
Customer customer = new Customer();
// populate the customer object
JAXBSource source = new JAXBSource(jc, customer);
schema.newValidator().validate(source);
}
}
For a more detailed example see:
- http://bdoughan.blogspot.com/2010/11/validate-jaxb-object-model-with-xml.html
You would have to map the Java object to xml, then marshall the object into xml, then feed the xml to a parser that does schema validation. Might be better to write code to parse the xml schema and read the schema, then use the schema information to build a validator for your object. That way you wouldn't have to marshall your object to xml just to validate it.
精彩评论