XML technologies / XML / Perl & XML / XML basics: Reading and writing / Validating documents
(Excerpt from “Perl & XML” by Erik T. Ray & Jason McIntosh)
XML well-formedness is a minimum requirement. Accepting that alone makes the program take much on faith. For a document intended for a specific application, a parser silently accepting an unknown element does us no favors. Fortunately, much better quality control is available: we can validate the document.
Validation is a sophisticated way to compare a document instance with a template or specified grammar. Element number, type and order can all be checked, even patterns in element and attribute character data. A validating parser reports whether the document is valid against a given DTD or schema by comparing them.
Remember that not every XML document needs validation. DTDs and other schemas are excellent for working with XML markup languages with an established schema, such as XHTML for web pages, MathML for mathematical equations, or CaveML for cave exploration. Their strict rules determine where elements and attributes are valid, offering automated feedback on your mistakes when needed.
Validation may be less useful for nonspecific Perl/XML tasks. It can get in the way when constructing XML at runtime. With a less clearly defined data format, this can also apply when reading and analyzing XML.
You may therefore be right to consider validation unnecessary or even harmful in some situations. With a complex, standardized XML dialect, however, accepting its extra cost is probably worthwhile. Your toolbox almost certainly offers relatively simple ways to do it. Read on.
DTDs
Document Type Definitions (DTDs) are documents written in a special markup language. Their syntax is defined by the XML specification, although a DTD itself does not use XML syntax. A DTD contains only declarations, all starting with <!. They declare elements, attributes, entities or notations.
The next example is a relatively simple DTD.
Example: A cute little DTD
<!ELEMENT memo (to, from, message)>
<!ATTLIST memo priority (urgent|normal|info) 'normal'>
<!ENTITY % text-only "(#PCDATA)*">
<!ELEMENT to %text-only;>
<!ELEMENT from %text-only;>
<!ELEMENT message (#PCDATA | emphasis)*>
<!ELEMENT emphasis %text-only;>
<!ENTITY myname "Ronald McDonald"> This DTD declares five elements, one attribute of the <memo> element, a parameter entity clarifying the other declarations, and an entity usable within the document. This is enough for a validating parser to accept or reject a document. The following would be valid:
<!DOCTYPE memo SYSTEM "/dtds/memo.dtd">
<memo priority="info">
<to>Chicken McNugget</to>
<from>&myname;</from>
<message>Hör auf, Memos zu lesen, und mach Dich an die Arbeit!</message>
</memo> Removing the element <to> would make the document invalid while it remained well-formed. Validation can therefore make sense.
Parsing a DTD is fairly easy, so most XML parsers can validate against one while parsing, for example XML::LibXML. The next example demonstrates how.
Example: A validating parser
use XML::LibXML;
use IO::Handle;
# Initialisierung des Parsers
my $parser = new XML::LibXML;
# Erzeugen eines Dateihandles und Aufruf des Parsers
my $fh = new IO::Handle;
if( $fh->fdopen( fileno( STDIN ), "r" )) {
my $doc = $parser->parse_fh( $fh );
if( $doc and $doc->is_valid ) {
print "Ja, das Dokument ist gültig.\n";
} else {
print "Krass! Das Dokument ist konkret ungültig.\n";
}
$fh->close;
}This parser can easily be used whenever reading a document. Unfortunately, it provides little detail when a document is invalid. We would like to know, for example, whether an element is misplaced. It is therefore unsuitable as a general validation tool.
The author prefers a small command-line tool called nsgmls. Public websites also offer validation. In that case the XML document needs a DOCTYPE declaration whose system identifier, if present, must be a publicly accessible URL rather than a local file path.
A better choice is the module XML::Checker by T. J. Mather, giving much more specific errors.
Schemas
DTDs have many limitations. They cannot check what kind of text an element contains or whether it matches a given pattern. A parser should ideally accept an element <datum> only if it really contained a date. That requires a better solution, such as XML Schema. XML Schema is a kind of second-generation DTD, offering much more versatile and flexible validation.
As noted in Introduction to XML, XML Schema has the dubious distinction of being the most controversial schema language. Many XML hackers favor schemas in principle but reject XML Schema as too complex or incomprehensible.
Alternatives include OASIS-Open’s RelaxNG and Schematron by Rick Jelliffe. Like XML Schema, they are XML-based languages describing other XML languages. With a suitable parser, their schemas validate other XML documents. We find Schematron especially interesting because Kip Hampton’s XML::Schematron is a family of Perl modules making it accessible.
Schematron rests on technologies with good Perl implementations, another benefit for Perl/XML hackers. It defines a very simple language specifying how particular things should look, based on XPath expressions. You need not specify a grammar anticipating everything that might occur. Instead, validate only selected parts. Elements and attributes can depend on entirely different document parts whenever XPath can express the relationship. In practice a Schematron document most resembles an XSLT stylesheet. This is deliberate: Schematron is designed for XSLT implementation. Indeed, this is how two of the XML::Schematron-modules operate, by first transforming the user’s schema into an XSLT-stylesheet, then checking the document with an XSLT processor.
Schematron has no built-in data types . A single word cannot, for example, require an attribute to use the W3C date format. But a Perl program can add a step, using XML::XPath or a good old Perl regular expression to verify the content of a <datum> element. No schema language supports checks against database contents or other actions outside the document. Combining Perl and schemas is very useful here.
Copyright © 2003 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “Perl & XML” is subject to the same conditions as the bound edition: the work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de