Shubham Chaurasia
Shubham Chaurasia

Reputation: 2622

Validation of XML through JAXB

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)

Upvotes: 3

Views: 1647

Answers (2)

Xstian
Xstian

Reputation: 8272

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

Below an example of Schema Validation.

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

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

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

Upvotes: 3

lexicore
lexicore

Reputation: 43651

Valid in a sense of XML validity (well-formed etc.) - yes.

Valid in a sense of a conformance to some XML Schema - no. Even if you've generated your classes out of this schema using XJC, the answer is no. Int might be invalid in that schema even if JAXB unmarshalls without errors.

If you want to make sure your XML conforms to your XML schema, you have to explicitly validate it. Here's a related question:

Validating against a Schema with JAXB

Upvotes: 2

Related Questions