【问题标题】:Validation of XML through JAXB通过 JAXB 验证 XML
【发布时间】:2014-11-28 05:58:57
【问题描述】:

如果一个 XML 文件被 JAXB 正确解组,我们可以说它是有效的吗? (当我们正确获取 POJO 对象时)

【问题讨论】:

  • 您让我们知道这是否可以正常工作。 :)

标签: xml validation jaxb


【解决方案1】:

在 XML 有效性的意义上有效(格式良好等)- 是的。

在符合某些 XML 模式的意义上是有效的 - 不。即使您已经使用 XJC 从这个模式中生成了类,答案也是 。即使 JAXB 解组时没有错误,Int 也可能在该架构中无效。

如果你想确保你的 XML 符合你的 XML 模式,你必须明确地验证它。这是一个相关的问题:

Validating against a Schema with JAXB

【讨论】:

    【解决方案2】:

    如果 Unmarshalled 工作正常,则 XML 格式正确,但如果您有 Schema,则可以添加 XSD 验证。

    下面是架构验证的示例。

      JAXBContext jaxbContext = JAXBContext.newInstance(new Class[]{Root.class});
      SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    
      //Source yourSchema.xsd
      InputStream xsdStream = CopyMetaInfos.class.getClassLoader().getResourceAsStream(SCHEMA);
      StreamSource xsdSource = new StreamSource(xsdStream);
    
      Schema schema = schemaFactory.newSchema(new StreamSource[]{xsdSource});
    
      Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
      unmarshaller.setSchema(schema);
      Root root = (Root) unmarshaller.unmarshal(is);
    

    此验证检查 XML 是否遵循架构的约束。

    例如(此元素必须为 0

    <xs:element name="age">
      <xs:simpleType>
        <xs:restriction base="xs:integer">
          <xs:minInclusive value="0"/>
          <xs:maxInclusive value="100"/>
        </xs:restriction>
      </xs:simpleType>
    </xs:element>
    

    例如(这个元素必须是强制性的)

    <xs:element name="child_name" type="xs:string" minOccurs="1"/>
    

    【讨论】:

    • 谢谢。所需要的只是一个格式良好的 XML,但可以根据我的项目要求对其进行验证。
    猜你喜欢
    • 2014-02-27
    • 2013-12-05
    • 2017-05-19
    • 2011-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多