我正在构建一个报告,该报告将显示与一组 XPath 匹配的 XML 元素的行号。我需要支持 XPath 2.0。将 XML 发送到用 Java 或 C# 编写的单独的基于 Web 的处理器是一种有效的解决方案,但我正在避免这种解决方案,因为我的整个团队都使用 Python 工作,我希望我的工具仍然可以离线工作,并且维护另一个 Web 服务非常繁琐工作。
Saxonche 支持 XPath 2.0。 文档描述了启用行号的多个选项,但从未解释启用后如何获取行号。
这是我的代码:
input_file_path = 'test.xml' # Contents below
input_xpath = './/foo'
with PySaxonProcessor(license=False) as saxon_proc:
# Attempt #1 to enable line numbers
saxon_proc.set_configuration_property('l', 'on')
doc_builder = saxon_proc.new_document_builder()
# Attempt #2 to enable line numbers
doc_builder.set_line_numbering(True)
xml_tree = doc_builder.parse_xml(xml_file_name=input_file_path)
xpath_processor = saxon_proc.new_xpath_processor()
xpath_processor.set_context(xdm_item=xml_tree)
foo_elements = xpath_processor.evaluate(input_xpath)
# Do not see any line numbers on foo_elements in the debugger
我在调试器中检查了
evaluate()
的结果,但我没有看到任何看起来像行号的东西。
PySaxonProcessor
和PyDocumentBuilder
都有一个parse_xml()
方法。在我的代码中,我使用 PyDocumentBuilder
,但我尝试了两者,但没有注意到任何差异。
测试.XML
<root>
<foo>fah</foo>
</root>
显然存在错误的方式将 XML 提供给 Saxon,这可能会导致没有行号,但我找到的所有相关信息都是其他语言的。
关于我做错了什么有什么想法吗?
恐怕我目前无法告诉 SaxonC HE 有一种方法,对于 PE/EE 你应该能够使用 Saxon XPath 扩展函数
saxon:line-number
例如
from saxoncee import PySaxonProcessor
with PySaxonProcessor(license=True) as saxon_proc:
print(saxon_proc.version)
doc_builder = saxon_proc.new_document_builder()
doc_builder.set_line_numbering(True)
xdm_doc = doc_builder.parse_xml(xml_file_name='sample1.xml')
xpath_processor = saxon_proc.new_xpath_processor()
xpath_processor.set_context(xdm_item=xdm_doc)
xpath_processor.declare_namespace('saxon', 'http://saxon.sf.net/')
items = xpath_processor.evaluate('//item')
for item in items:
xpath_processor.set_context(xdm_item=item)
print(item, xpath_processor.evaluate_single('saxon:line-number(.)'))
正如我所说,我目前不确定SaxonC HE是否有办法,会尝试调查。