【问题标题】:Validate XML with namespaces against Schematron using lxml in Python在 Python 中使用 lxml 针对 Schematron 验证带有命名空间的 XML
【发布时间】:2019-10-22 03:53:54
【问题描述】:

我无法让 lxml Schematron 验证器识别名称空间。验证在没有命名空间的代码中可以正常工作。

这适用于 MacOS 10.15 上的 Python 3.7.4 和 lxml 4.4.0

这是schematron文件

<?xml version='1.0' encoding='UTF-8'?>
<schema xmlns="http://purl.oclc.org/dsdl/schematron"
  xmlns:ns1="http://foo">
  <pattern>
    <rule context="//ns1:bar">
      <assert test="number(.) = 2">
       bar must be 2
      </assert>
    </rule>
  </pattern>
</schema>

这里是xml文件

<?xml version="1.0" encoding="UTF-8"?>
<zip xmlns:ns1="http://foo">
    <ns1:bar>3</ns1:bar>
</zip>

这是python代码

from lxml import etree, isoschematron
from plumbum import local
schematron_doc = etree.parse(local.path('rules.sch'))
schematron = isoschematron.Schematron(schematron_doc)
xml_doc = etree.parse(local.path('test.xml'))
is_valid = schematron.validate(xml_doc)
assert not is_valid 

我得到:lxml.etree.XSLTParseError: xsltCompilePattern : failed to compile '//ns1:bar'

如果我从 XML 文件和 Schematron 文件中删除 ns1,该示例将完美运行——没有错误消息。

在我缺少的 lxml Schematron 中注册命名空间必须有一个技巧。有人做过吗?

【问题讨论】:

    标签: python validation lxml xml-namespaces schematron


    【解决方案1】:

    事实证明,有一种在 Schematron 中注册命名空间的特定方法。在Schematron ISO standard中有描述

    只需要对 Schematron 文件稍作改动,添加“ns”元素如下:

    <?xml version='1.0' encoding='UTF-8'?>
    <schema xmlns="http://purl.oclc.org/dsdl/schematron">
      <ns uri="http://foo" prefix="ns1"/>
      <pattern>
        <rule context="//ns1:bar">
          <assert test="number(.) = 2">
           bar must be 2
          </assert>
        </rule>
      </pattern>
    </schema>
    

    我不会删除这个问题,因为没有使用命名空间的 Schematron 规则示例。希望它可以对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-18
      • 2019-07-26
      相关资源
      最近更新 更多