Home > Articles

Validation of XML in Data-Centric Systems

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:complexType>
      <xsd:sequence>
        <xsd:element name="height" type="xsd:integer"/>
      </xsd:sequence>
      <xsd:attribute name="working" type="xsd:boolean"/>
      <xsd:assert test="if (@working eq true())
                       then height &lt; 10
                       else false()"/>
    </xsd:complexType>
  </xsd:element>
</xsd:schema>

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">
<height>5</height>
</booleantest>

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">
<height>50</height>
</booleantest>

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

Exception: cvc-assertion.3.13.4.1: 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">
<height>5</height>
</booleantest>

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

Exception: cvc-assertion.3.13.4.1: 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.

Conclusion

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020