4

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 string32 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.

Istao
  • 7,425
  • 6
  • 32
  • 39

2 Answers2

3

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:

bdoughan
  • 147,609
  • 23
  • 300
  • 400
1

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.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
  • 1
    Seems to me to be a one year man job !! Is there a library to do that, or can you provide a simple exemple ?? Thanks. – Istao Nov 18 '10 at 20:02
  • 1
    Check out my answer how this can be done with the javax.xml.validation library: http://stackoverflow.com/questions/4218935/checking-a-java-value-with-an-xml-schema/4219090#4219090 – bdoughan Nov 18 '10 at 20:11