Checking java value with xml schema

Is it possible to check the value in a java object with some rules in xml schéma?

For example, I have String txt = "blablabla" , and I have to check if this is normal for <xs:element name="foo" type="string32"/> , and string32 is a limit of 32 caract. length max.

Is it possible? If this is not possible with xml schema and jaxb, is there a possible variant of langage schema?

Thanks.

+4
source share
2 answers

You can 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

+2
source

You would need to map the Java object to xml, then put the object in xml, and then pass the XML to the parser that performs the schema validation. It might be better to write code to analyze the xml schema and read the schema, and then use the schema information to create a validator for your object. This way, you would not need to march your object in xml to validate it.

+1
source

All Articles