Home > Articles

Validation of XML in Data-Centric Systems

  • Print
  • + Share This
Data validation remains an un-sexy part of software development. In spite of its importance to the success of so many systems, validation is often added as a nearly optional and sometimes poorly crafted extra. Omitting solid XML validation is dangerous. It's also unnecessary, because XML Schema 1.1 offers compelling data-management features that simplify validation, as Stephen B. Morris explains.
Like this article? We recommend

In this data-rich era, the role of data-centric applications is a central plank in enterprise IT. Many organizations are scrambling to mine both their own data assets and publicly accessible assets. We can only speculate on how our social media data is being consumed and analyzed. The enthusiasm for data mining seems to be exceeded only by the appetite for self-publication that so many social media users display! I imagine that this trend will eventually sputter out, as social media users begin to see the nefarious ways in which their data is being used. But there most likely will remain a massive generational digital footprint.

XML and Data

Many organizations use XML as their principal data-representation tool. Of course, JSON is probably the trendy format, given its important role in more lightweight programming languages such as Python and JavaScript. But XML remains a staple of several large industries because of its maturity and associated toolchain.

Sometimes critics of XML point to the relative bulkiness of the language, and they have a point. Indeed, the size of XML messages formerly was often cited as an unnecessary consumer of network bandwidth, though the ubiquity of high-speed networks makes this less of an issue nowadays. Perhaps, a more relevant criticism of XML might be the visual complexity of the finished documents.

More serious is the fact that XML users must take steps to avoid nasty attacks, such as XML External Entity (XXE) and tag-insertion attacks.

In spite of these concerns, XML has some very useful attributes, specifically in the twin areas of design and data management. In this article, we'll explore some of the interesting data-modeling features provided by XML Schema 1.1.

This article continues the overall theme of validation from my previous article "Java Data Validation Using Hibernate Validator." This time around, I'll look at XML data validation in the context of schema definition and Java code.

Data Modeling and Validation

For data-centric systems, modeling is a key element (perhaps the key element) of the entire design. If the system is message-based, it makes sense to build the design around the message model definition. Defining the messages is therefore a solid step in the direction of system design. The application-specific protocol for exchanging the messages is another key part of the design. Between these two phases lies another sub-phase, which is the design of a validation mechanism.

Sometimes added late in the development cycle, validation is possibly the most important part of any data-centric system. Get the validation wrong, and the system and/or its users can be compromised. (You can be fairly certain that neither system admins nor end users will thank you for compromising their interests.)

A key aspect of validation is the enforcement of multi-field constraints; that is, where two or more fields in a web page form have a functional relationship. This type of relationship is termed a co-occurrence constraint. For example, suppose form field X is a Boolean type and form field Y is an integer. The co-occurrence constraint might be that if field X is clicked (it has the value true), then field Y should not be editable above a certain value. In other words, the two data items are related to each other.

Before digging into creating such constraints, let's look briefly at the twin areas of coding and design. This is important because it's useful to view data modeling and design in isolation from back-end or integration coding.

Coding Versus Design

Perhaps one of the most surprising aspects of modern IT practice is the confusion that seems to exist between coding and design. It's not uncommon for senior developers to view design and its documentation as a tiresome chore that can be safely skipped! I believe this increasingly widespread mindset is dangerous and potentially a destroyer of opportunity.

This modern lack of interest in design may be due, in part, to the global migration toward agile development, where working code is seen as the principal deliverable. However, a good design can inform coding and help with important programming decisions. An example of the latter is the way a solid design can provide a useful coarse-grained mental framework for the overall code structure. I would argue that the fine-grained nature of coding makes it more difficult to produce such a mental framework for the overall code structure. Data validation is therefore a key design exercise!

XML Schema 1.1

Let's take a look at an important XML design artifact: the XML schema document. In particular, I'll discuss some XSD 1.1 features, rather than the legacy XSD 1.0 case. Version 1.1 provides support for co-occurrence constraints.

Listing 1 illustrates an example XSD schema document. If you're not very familiar with XSD, think of the contents of Listing 1 as a data description model. This is another way of saying that it's metadata (data about data).

Listing 1—A simple XSD 1.1 schema document with data and rules.

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="attributeFormDefault=">
  <xsd:element name="booleantest">
        <xsd:element name="height" type="xsd:integer"/>
      <xsd:attribute name="working" type="xsd:boolean"/>
      <xsd:assert test="if (@working eq true())
                       then height &lt; 10
                       else false()"/>

The XSD document in Listing 1 describes our data model, which is defined inside an element called booleantest. Think of the booleantest element as an overall container for the data model. The data itself is defined inside an XSD complexType, which is analogous to a programming language datatype definition, such as a C struct.

Our Listing 1 complexType contains a single data item: an integer called height. This data item is contained inside a sequence. The sequence is followed by the declaration of an attribute called working, with boolean type.

Data and Code Nexus

The interesting section of Listing 1 is the next part, which is contained inside the assert tag. The latter tag contains the logic required to test the data model. The logic inside the assert tag is pretty straightforward XPath code:

"if (@working eq true())
     then height &lt; 10
     else false()"

This code basically expresses the rule that if the value of the attribute working is true and the value of height is less than 10, the data passes validation. Of course, these values (true and 10) are completely arbitrary and can be changed to suit the application. If the form values are outside the required range, the schema data validation fails. We'll see in a moment how this situation is handled.

The data model is implemented using an XML instance document. Thanks to its similarity to HTML, the latter is probably familiar territory. Listing 2 contains an example instance document.

Listing 2—A simple XML instance document.

<?xml version="1.0" encoding="UTF-8"?>
<booleantest working="true">

In Listing 2, notice that the data items match those specified in Listing 1. Now how do we bring together all this information and actually see some real validation code in action? Good question. Listing 3 shows a Java program that executes an XSD validation of the XML instance document.

Listing 3—Java code and XSD validation.

public class XMLValidation {
    public static void main(String[] args) {
      try {
          System.out.println("Result of validation against Model.xsd is: "
+validateXSDSchema("C:\\, "C:\\validation \\ApplicationData.xml")); } catch (Exception e) { System.out.println("Caught exception: " + e.toString()); } } public static boolean validateXSDSchema(String xsdDocPath, String xmldocPath){ try { SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/XML/XMLSchema/v1.1"); Schema schema = factory.newSchema(new File(xsdDocPath)); Validator validator = schema.newValidator(); validator.validate(new StreamSource(new File(xmldocPath))); } catch (IOException | SAXException e) { System.out.println("Exception: " +e.getMessage()); return false; } return true; }

In Listing 3, notice the use of a v1.1 schema in the call to SchemaFactory.newInstance(). An instance of the class Schema is created from the SchemaFactory object. A Schema object is an immutable in-memory representation of a designated grammar (in this case, XML Schema 1.1). This object provides a set of constraints that can be applied against an XML instance document.

When I run the code in Listing 3, using the two files in Listings 1 and 2, I get the following result:

Result of validation against Model.xsd is: true

In other words, the schema rules and the instance document are in agreement—this data is okay. Now suppose I change the XML data as shown in Listing 4.

Listing 4—A modified XML instance document to break the co-occurrence constraint.

<?xml version="1.0" encoding="UTF-8"?>
<booleantest working="true">

If I re-run the Java program, I get this result:

Exception: cvc-assertion. Assertion evaluation ('if (@working eq true())
  then height < 10 else false()') for element 'booleantest' with type '#anonymous' did not succeed.
Result of validation against Model.xsd is: false

The key part in the result above is the Boolean return value in the last line, which indicates that the data has failed validation. This happens because the value of height in Listing 4 is 50, while the schema rule in Listing 2 requires a value less than 5.

What happens if my XML instance document has the Boolean attribute set to false, as in Listing 5?

Listing 5—A further modification to the XML instance document.

<booleantest working="false">

As expected, re-running the Java code produces another validation failure:

Exception: cvc-assertion. Assertion evaluation ('if (@working eq true())
  then height < 10 else false()') for element 'booleantest' with type '#anonymous' did not succeed.
Result of validation against Model.xsd is: false

This is quite a lot of power in a few lines of code. The XPath code embedded in the model allows us to examine our related data items easily, and this example can be extended to handle a much larger and more complex data model. The following section details the required dependencies and tools needed to run the code.

Required Tools

To run the above Java code in Eclipse (or one of the other IDEs), you'll need the following dependencies:

  • xml-apis.jar
  • xercesImpl.jar
  • org.eclipse.wst.xml.xpath2.processor_1.1.0.jar
  • cupv10k-runtime.jar

All of these items are available as part of a single download of the Apache Xerces2 XML parser [Xerces2 Java 2.11.0 (XML Schema 1.1) (Beta)] and its related components. I ran the Java code as an Eclipse project with the previously stated dependencies. The XSD file and the XML instance document must also be available to the Java code.

The XML and XSD editing tools in Eclipse are adequate for examining and modifying the code. Other options are available, both open source and proprietary.

Code and Data in Close Proximity

Adding validation directly to a data model has certain benefits. One is that the designer can focus on the data requirements without being distracted by other code considerations. In this case, the data model returned a simple Boolean value based on the asserted data relationships. If required by the application, these relationships can be made far more complex than those shown in Listing 1. This division between data and its associated validation rules can be thought of as a useful separation of concerns. Beyond that is the notion of separation of disciplines; in this example, data design and Java coding. An XSD/XML data designer in this context need not be a Java expert.

The Java code that invokes the validation mechanism is agnostic in terms of the data relationships. The supplied data either works or it doesn't. Therefore, the Java programmer doesn't need to be too concerned with the potential complexities of the data model.

This fact also illustrates the notional separation of disciplines—if required, a data designer can work in isolation from a back-end Java programmer. They don't have to be different people, but it's an interesting possibility.

Comparison with Hibernate Validator

An XSD/XML approach to data modeling is different from one based on Hibernate Validator. With the latter, the Java data model itself is annotated with constraints. Then a runtime Java validator applies the required rules and gives the results. In other words, with Hibernate Validator the validation facilities are quite close to the back-end Java code—it's all Java.

Perhaps one merit of the XSD/XML approach is the fact that it doesn't dictate Java as the processing language. Any language with an appropriate binding to Xerces2 will work.

The other advantage of the XSD/XML model is that a non-programmer, with a little effort and training, could handle the data modeling and validation definition.

Online XSD Validation

The W3C website has a link to an online tool for XSD validation. This utility allows you to supply an XSD and an XML instance-document pair. The tool then verifies whether the documents are compatible and well-formed.


XML remains a viable approach to data modeling. Users of this technology must be vigilant in relation to parser-based attacks, such as XXE and tag insertion. Such attack methods are part of the cost of using most technologies.

The XML Schema 1.1 features some useful data modeling and validation facilities. In particular, co-occurrence constraints can be handled with relative ease. Adding this type of capability to XSD allows for the possibility of leaving the data to the data experts (the business system analysts). Very often, such experts have the deepest knowledge of the data domain. It may make sense to leave the data definition and validation to these analysts, and XSD 1.1 provides this option.

Running the validation code from Java code is pretty easy, and we get a simple Boolean result based on the defined rules. This is similar to how Hibernate Validator works; however, in XML Schema we have a nice separation between the data and the back-end Java code. I believe this is why XML remains a viable option.

  • + Share This
  • 🔖 Save To Your Account