Skip to content

Instantly share code, notes, and snippets.

@ohsh6o
Last active October 6, 2020 19:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ohsh6o/2f88f358f97764f2ce26801a13ca1b3b to your computer and use it in GitHub Desktop.
Save ohsh6o/2f88f358f97764f2ce26801a13ca1b3b to your computer and use it in GitHub Desktop.
Schematron Example from stackoverflow.com/q/27150214
from io import StringIO
from lxml import isoschematron
from lxml import etree
def main():
# Example adapted from http://lxml.de/validation.html#id2
# Schema
f = StringIO('''\
<schema xmlns="http://purl.oclc.org/dsdl/schematron" >
<pattern id="sum_equals_100_percent">
<title>Sum equals 100%.</title>
<rule context="Total">
<assert test="sum(//Percent)=100">Sum is not 100%.</assert>
</rule>
</pattern>
</schema>
''')
# Parse schema
sct_doc = etree.parse(f)
schematron = isoschematron.Schematron(sct_doc, store_report = True)
# XML to validate - validation will fail because sum of numbers
# not equal to 100
notValid = StringIO('''\
<Total>
<Percent>30</Percent>
<Percent>30</Percent>
<Percent>50</Percent>
</Total>
''')
# Parse xml
doc = etree.parse(notValid)
# Validate against schema
validationResult = schematron.validate(doc)
# Validation report
report = schematron.validation_report
print("is valid: " + str(validationResult))
print(type(report))
print(report)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment