Version 4 of XSD schema validate an XML document

Updated 2010-06-17 14:50:57 by pgaubatz

Given an XML Schema how do I use it to schema-validate an instance XML document?

Answer: to do this you need to read and parse both documents, compile the schema and then use the compiled schema to validate the instance document.

package require xml ;# you need to install TclXML/libxml2 v3.2 or better

# First read and parse the schema document

set ch [open "schema.xsd"]
set schemaxml [read $ch]
close $ch
set schemadoc [dom::parse $schemaxml]

if 0 {
Next compile the schema so that it is ready to perform schema-validations.
There might be something wrong with the schema document, so use the catch command to handle that.
}

if {[catch {$schemadoc schema compile} msg]} {
    puts stderr "something is wrong with the XSD schema: $msg"
    exit
}


if 0 {
Now read and parse the instance (data) document. This is the document that you are trying to test is schema-valid against the XSD schema.
}

set ch [open "document.xml"]
set xml [read $ch]
close $ch
set doc [dom::parse $xml]

if 0 {
Everything is now ready to perform the schema-validation. If validation succeeds, the command will return a success code.
If the document is invalid, the command will return an error code and the result will contain a description of why the document is invalid.
}

if {[catch {$schemadoc schema validate $doc} msg]} {
    puts "document is invalid"
} else {
    puts "document is valid"
}

pgaubatz - 2010-06-17 10:50:57

Any ideas how to validate an XML document against multiple XML schemas?