xml-schema-validation-with-python

xml schema validation with python

System Requirements For Debian/Ubuntu:
1) dependencies
   
sudo apt-get install libxml2-dev libxslt-dev python-dev

2) package
   
sudo apt-get build-dep python3-lxml

Python:
1) PIP Package:
   
pip install lxml
Xml-Schema-Validator.py
 
from lxml import etree

def validate(xmlparser_xsd, xml_data):
    try:
        etree.fromstring(xml_data, xmlparser_xsd)
        return True
    except etree.XMLSchemaError:
        return False

# xml schema
xml_schema_file = "xml_schema.xsd"
with open(xml_schema_file, 'r') as xml_schema_file:
    schema_root = etree.XML(xml_schema_file.read())

schema = etree.XMLSchema(schema_root)
xmlparser = etree.XMLParser(schema=schema)

xml_file = "xml_file.xml"
with open(xml_file, 'r') as xml_file:
    xml_data = xml_file.read()
    if validate(xmlparser, xml_data):
        print "Valid"
    else:
        print "Invalid"

Buy a product to Support me