Checking a java value with an xml schema

北城余情 提交于 2020-01-03 17:08:14

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/4218935/checking-a-java-value-with-an-xml-schema

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!