Kotlin, Software Development

Kotlin – Validate XML Against Multiple XSDs

This post shows how to validate an XML file against multiple XSDs in Kotlin wherein one XSD is included in another XSD file.

Requirements

We used the following items for this post.

  1. Java JDK 14
  2. IntelliJ IDEA 2020.3
  3. Kotlin 1.3.72

Our Multiple XML Schemas In XSD files

For this post, we use two XML schemas in separate XSD files. One of them being the main XML schema called myschema.xsd, while the other is a dependent XSD XML schema.

The dependent XSD file, my-other-schema.xsd, has the following contents. It defines the OtherInfo element, which has two string elements city and country.

To use (or reuse) the OtherInfo element in another XSD file to validate XMLs, we use the <xs:include schemaLocation="my-other-schema.xsd"/>, as shown and highlighted below.

Note on line 3; we included the dependent XSD in myschema.xsd. These files must be in the same directory. In this post, the XSD and the test XML files are all in the project’s resources folder.

XML to Validate Against Multiple XSDs

Then, we craft an XML file to validate against our XSDs files. The XML file contains three names and an OtherInfo element. Note that the name elements have to be unique because we use the main XSD file’s unique constraint.

Kotlin Codes

Next, we write our main Kotlin codes similar to the following codes to validate XML Against Multiple XSDs.

DEMO: Validate XML Sample Against XSDs

When we run the codes, we get the following output on the console window in the IDE.

Kotlin Validate XML against XSDs

The Kotlin codes are not ideal, but they show how to validate an XML against multiple XSDs. When referencing files in the resources folder, we need to prepend the file name with “/”; otherwise, the Kotlin codes will return NullPointerException. For example, /myschema.xsd instead of just  myschema.xsd.

That is all for now. Thank you!

You Might Also Like