使用xml架构检查java值 [英] Checking a java value with an xml schema
本文介绍了使用xml架构检查java值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使用xmlchéma中的某些规则检查java对象中的值?
is it possible to check a value in a java object with some rules in a xml schéma ?
例如,我有一个字符串txt =blablabla
,我应该验证它是否适用于< xs:element name =footype =string32/>
,string32限制为32 caract。最长
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.
有可能吗?如果使用xml架构和jaxb是不可能的,那么还有其他架构可能吗?
Is it possible ? If it's not possible with xml schema and jaxb, is there other schema langage which is possible ?
谢谢。
推荐答案
您可以执行以下操作:
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
这篇关于使用xml架构检查java值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文