Created
October 22, 2009 10:17
-
-
Save iiska/215879 to your computer and use it in GitHub Desktop.
Simple XML Schema validator in Python using lxml library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/python | |
# -*- coding: utf-8 -*- | |
# | |
# Simple XML validator done while learning the use of lxml library. | |
# -- Juhamatti Niemelä <iiska AT iki DOT fi> | |
import lxml | |
from lxml import etree | |
if __name__ == "__main__": | |
import sys, os | |
if len(sys.argv) != 3: | |
print "Usage: %s document.xml schema.xsd" % (sys.argv[0]) | |
exit(0) | |
with open(sys.argv[2]) as f: | |
doc = etree.parse(f) | |
print "Validating schema ... " | |
try: | |
schema = etree.XMLSchema(doc) | |
except lxml.etree.XMLSchemaParseError as e: | |
print e | |
exit(1) | |
print "Schema OK" | |
with open(sys.argv[1]) as f: | |
doc = etree.parse(f) | |
print "Validating document ..." | |
try: | |
schema.assertValid(doc) | |
except lxml.etree.DocumentInvalid as e: | |
print e | |
exit(1) | |
print "Document OK" |
In het "upper" schema you import the other xsd's, as long as path is set right (in the upper xsd) it will work.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Does this work with a schema that references (i.e. with attribute like schemaLocation = "base.xsd") another schema? If not, do you know how to do it?