繁体   English   中英

使用 Python 中的 lxml 针对 Schematron 使用命名空间验证 XML

[英]Validate XML with namespaces against Schematron using lxml in Python

我无法让 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 中注册命名空间必须有一个技巧。 有人做过吗?

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

它只需要对 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 规则示例。 希望它可以对某人有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM