Python 中使用 lxml 进行 Schematron 验证:如何检索验证错误?

2024-04-15

我正在尝试使用 lxml 进行一些 Schematron 验证。对于我正在处理的特定应用程序,重要的是报告任何未通过验证的测试。这lxml文档 http://lxml.de/validation.html提到了存在validation_report属性对象。我think这应该包含我正在寻找的信息,但我只是不知道如何使用它。这是一些演示我的问题的示例代码(改编自http://lxml.de/validation.html#id2 http://lxml.de/validation.html#id2;使用 Python 2.7.4 进行测试):

import StringIO
from lxml import isoschematron
from lxml import etree

def main():

    # Schema
    f = StringIO.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.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 (assuming here this is where reason 
    # for validation failure is stored, but perhaps I'm wrong?)
    report = isoschematron.Schematron.validation_report

    print("is valid: " + str(validationResult))
    print(dir(report.__doc__))

main()

现在,从值validationResult我可以看到验证失败(如预期),所以接下来我想知道why。第二个打印语句的结果给了我:

['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__
format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__get
slice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mo
d__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
 '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook
__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center',
 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index
', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper',
'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', '
rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', '
strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

据我所知,根据文档和这个相关问题 https://stackoverflow.com/questions/10963206/schematron-report-issue-with-python-lxml。很可能是我忽略的一些非常明显的事情吗?


好的,Twitter 上有人给了我一个建议,这让我意识到我对 schematron 类的引用完全错误。由于似乎没有任何明确的示例,我将在下面分享我的工作解决方案:

import StringIO
from lxml import isoschematron
from lxml import etree

def main():
    # Example adapted from http://lxml.de/validation.html#id2

    # Schema
    f = StringIO.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.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()

The print该报告的声明现在产生以下输出:

 <?xml version="1.0" standalone="yes"?>
<svrl:schematron-output xmlns:svrl="http://purl.oclc.org/dsdl/svrl" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:schold="http://www.ascc.net/xml/schematron" xmlns:sch="http://www.ascc.net/xml/schematron" xmlns:iso="http://purl.oclc.org/dsdl/schematron" title="" schemaVersion="">
  <!--   
           
           
         -->
  <svrl:active-pattern id="sum_equals_100_percent" name="Sum equals 100%."/>
  <svrl:fired-rule context="Total"/>
  <svrl:failed-assert test="sum(//Percent)=100" location="/Total">
    <svrl:text>Sum is not 100%.</svrl:text>
  </svrl:failed-assert>
</svrl:schematron-output>

这正是我一直在寻找的!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 中使用 lxml 进行 Schematron 验证:如何检索验证错误? 的相关文章

随机推荐

  • CKEditor 5 通过外部 url 插入图像

    我想知道如何仅通过 URL 插入图像 用户从其他网站获取它 我需要实现一个简单的img 源 在 CKEditor 5 中 问题是 默认情况下 编辑器要求我上传图像 而我需要插入外部 url 我读过很多相关主题 1 https stackov
  • 带正文的 HttpDelete

    我正在尝试使用 HttpDelete 对象来调用 Web 服务的删除方法 Web 服务的代码从消息正文中解析 JSON 但是 我无法理解如何将主体添加到 HttpDelete 对象 有没有办法做到这一点 使用 HttpPut 和 HttpP
  • Python 的“导入”内部是如何工作的?

    当您导入一个模块 然后再次重新导入它时 它会被重新导入 覆盖还是跳过 当您导入模块 a 和 b 并且还在模块 a 中导入模块 b 时 会发生什么 这样做安全吗 例如 如果该模块 b 中有一个实例化的类 您最终会实例化它两次吗 import加
  • 我在使用阴影效果时表现不佳

    我在滚动视图上放置了一些图像视图 当我拖动这个滚动视图时 我没有遇到任何问题 但是 当我对这些图像视图应用阴影效果后 拖动此滚动视图的性能很差 我使用了shadowOpacity shadowRadius 和shadowOffset 方法
  • 使用流迭代 n 次,而不是使用 for 循环创建 n 项

    假设我想创建 n 个项目 在 Java 8 之前 我会这样写 List
  • 如何构建特定函数调用的图表?

    我有一个项目 我想动态构建特定函数调用的图表 例如 如果我有 2 个模板类 A 和 B 其中 A 有一个跟踪方法 保存为图形节点 B 有 3 个方法 非跟踪方法 跟踪方法和调用 A 的跟踪方法的跟踪方法 那么我希望能够仅将跟踪的方法调用注册
  • PyAudio 输入溢出

    我正在尝试用 python 发出实时绘图声音 我需要从我的麦克风中获取数据块 使用 PyAudio 尝试使用 import pyaudio import wave import sys chunk 1024 FORMAT pyaudio p
  • 查找字符串的*最*常见前缀 - 更好的方法吗?

    我有一个钥匙列表 foo a foo b foo c fnord 这里所有类似的解决方案都假设您没有fnord在你的文字中 我有这个代码可以完成这项工作 def detect prefix keys PCT 0 70 cutof pre l
  • 获取“/”字符后的字符串

    我想在 PostgreSQL SELECT 查询中提取字符 后面的字符串 字段名称是source path 表名是movies history 数据示例 source path 的值 184738 file1 mov 194839 file
  • 将 MATLAB 绘图转换为图像

    我生成了一个类似的情节 figure hold axis 0 10 0 10 fill 1 1 5 5 5 1 1 5 b 现在我想将此图作为矩阵 以便我可以用高斯过滤博客 谷歌搜索我发现了这个线程将绘图光栅化为图像 http www ma
  • 如何在 Struts2 中检查 s:if 中的字符串不等式

    我在用
  • android OpenGL ES简单图块生成器性能问题

    遵循这个问题 老式 2D 类似塞尔达传说游戏的最佳方法 https stackoverflow com questions 2125354 best approach for oldschool 2d zelda like game 感谢之
  • 在 log(n) 时间内查找排序数组中至少出现 k 次的元素

    给定一个由 n 个元素和一个数字 k 组成的排序数组 是否有可能在 log n 时间内找到出现超过 k 次的元素 如果有多个数字出现超过 k 次 则其中任何一个都可以接受 如果是 怎么办 编辑 我能够在线性时间内解决这个问题 并且我很高兴在
  • 如何从命令行列出已安装的 MSI? [关闭]

    Closed 这个问题是无关 help closed questions 目前不接受答案 我们最近将 Windows 软件包从 RPM cygwin 切换到 MSI wix 拥有原生包装是一个非常受欢迎的变化 我们打算坚持下去 然而 MSI
  • 使用 JQuery 将事件处理程序添加到 iframe

    我想将 keydown 事件处理程序分配给 iframe 类似于纯JS的东西 document getElementById iframe id contentWindow addEventListener keydown funcName
  • 生成加权随机数

    我正在尝试设计一种 好的 方法从一系列可能的数字中选择一个随机数 其中该范围内的每个数字都被赋予一个权重 简单地说 给定数字范围 0 1 2 选择一个数字 其中 0 有 80 的概率被选中 1 有 10 的概率 2 有 10 的概率 自从我
  • Angular - Google 未定义?

    你好 我正在尝试实施google maps api in angular 这很简单angularjs但我不知道什么不起作用 我有一个简单的应用程序 它显示产品及其位置 单击位置后 该位置会显示在地图上 但我正在使用的购物地图google m
  • R 中曲线下增量面积 (iAUC)

    曲线下面积可以使用以下公式计算trapz的功能pracmaR iAUC 中的包在许多情况下更加准确 特别是在生物学中 然而据我所知 没有 R 函数可以计算这个 陷阱函数如下 Example a lt c 1 4 5 6 b lt c 2 4
  • 如何使用 apache 设置 mpeg dash 服务器?

    我想在 ubuntu 10 04 上设置本地 mpeg dash 服务器 那么分别安装apache和mpeg dash编码器后该怎么办呢 thanks 只需将 MPD 和破折号段放入 apache htdocs 文件夹即可 如果您的 MPD
  • Python 中使用 lxml 进行 Schematron 验证:如何检索验证错误?

    我正在尝试使用 lxml 进行一些 Schematron 验证 对于我正在处理的特定应用程序 重要的是报告任何未通过验证的测试 这lxml文档 http lxml de validation html提到了存在validation repo