是否可以使用xmlchéma中的某些规则检查java对象中的值?
例如,我有String txt = "blablabla"
,我应该验证<xs:element name="foo" type="string32"/>
是否正常,string32限制为32 caract。长度最大
有可能吗?如果使用xml架构和jaxb是不可能的,那么还有其他架构可能吗?
感谢。
答案 0 :(得分:2)
您可以执行以下操作:
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);
}
}
有关更详细的示例,请参阅:
答案 1 :(得分:1)
您必须将Java对象映射到xml,然后将对象编组为xml,然后将xml提供给执行模式验证的解析器。编写代码来解析xml架构并读取架构可能更好,然后使用架构信息为您的对象构建验证器。这样你就不必将你的对象编组为xml而只是为了验证它。