gpt4 book ai didi

python - 在 Python 中使用 lxml 根据 Schematron 验证带有命名空间的 XML

转载 作者:行者123 更新时间:2023-12-01 23:31:38 25 4
gpt4 key购买 nike

我无法让 lxml Schematron 验证器识别命名空间。验证在没有命名空间的代码中运行良好。

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

这是架构文件

<?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 中注册命名空间一定有一个我所缺少的技巧。有人做过吗?

最佳答案

事实证明,有一种特定的方法可以在 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 规则的示例。希望它对某人有帮助。

关于python - 在 Python 中使用 lxml 根据 Schematron 验证带有命名空间的 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58496860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com