【问题标题】:Checking a java value with an xml schema使用 xml 模式检查 java 值
【发布时间】:2010-11-25 03:49:34
【问题描述】:

是否可以使用 xml 架构中的一些规则检查 java 对象中的值?

例如,我有一个String txt = "blablabla",我应该验证<xs:element name="foo" type="string32"/> 是否可以,string32 限制为 32 个字符。最大长度。

有可能吗?如果 xml 架构和 jaxb 无法实现,是否还有其他可能的架构语言?

谢谢。

【问题讨论】:

    标签: java xml xsd jaxb


    【解决方案1】:

    您可以执行以下操作:

    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);
        }
    
    }
    

    更详细的例子见:

    【讨论】:

      【解决方案2】:

      您必须将 Java 对象映射到 xml,然后将对象编组到 xml,然后将 xml 提供给进行模式验证的解析器。编写代码来解析 xml 模式并读取模式可能会更好,然后使用模式信息为您的对象构建验证器。这样您就不必为了验证它而将您的对象编组为 xml。

      【讨论】:

      • 在我看来是一份一年的工作!!有没有图书馆可以做到这一点,或者你能提供一个简单的例子吗?谢谢。
      • 查看我的回答如何使用 javax.xml.validation 库来完成:stackoverflow.com/questions/4218935/…
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-15
      • 2012-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多