[在Python中使用lxml针对Schematron验证具有名称空间的XML

问题描述 投票:0回答:1

我无法获得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:无法编译'// ns1:bar'

如果我从XML文件和Schematron文件中都删除ns1,该示例将正常运行-没有错误消息。

我缺少在lxml Schematron中注册名称空间的技巧。有人做过吗?

python validation lxml xml-namespaces schematron
1个回答
0
投票

事实证明,有一种在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规则的示例。希望它会对某人有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.