Last active
October 6, 2020 19:08
-
-
Save ohsh6o/2f88f358f97764f2ce26801a13ca1b3b to your computer and use it in GitHub Desktop.
Schematron Example from stackoverflow.com/q/27150214
This file contains hidden or 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
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