通过JAXB验证XML [英] Validation of XML through JAXB

查看:93
本文介绍了通过JAXB验证XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If an XML file is correctly Unmarshalled by JAXB, can we say that it is a valid? (As we are getting the POJO object correctly)

推荐答案

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

If Unmarshalled works fine the XML is well formed, but you can add a XSD validation if you have a Schema.

下面的模式验证示例。

  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遵循模式的约束,则此验证检查。

This validation checks, if XML follow the constraints of the schema.

例如(此元素必须为0< = x< = 10)

e.g (this element must be 0 <= x <= 10)

<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>

例如(此元素必须为必填项)

e.g (this element must mandatory)

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

这篇关于通过JAXB验证XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆