Evaluate Xpath2.0 in python

隐身守侯 提交于 2020-05-29 03:18:06

问题


I have an XPath expression as shown below.

if(replace(//p[1]/text(),'H','h') = 'hello') then //p[1]/text() else if(//p[1]/text() = 'world') then //p[2]/text() else 'notFound'

I want to display which 'if ' expression worked.

e.g //p[1]/text() if first 'if' expression worked.

'If' expression can have nested if, for loops and xpath2.0 functions.

I can't find any xpath2.0 library for python. So I tried to convert this Js library to python still I can able to split xpath2.0 expression to lexers but can't convert it fully to python.

Suggest me some Xpath2.0 library for python, if available. Also how to interpret XPath expression and display which part of the expression worked?


回答1:


As you already know, lxml, the cornerstone of Python's XML/XPath support, features only

XPath 1.0, XSLT 1.0 and the EXSLT extensions through libxml2 and libxslt

We still have some options.

I researched this topic recently (specifically, Python's XQuery support).
See the W3C for a reference list of XML Query Implementations.

  1. Python Modules with XPath 2+ and EXSLT Extensions (e.g. an EXSLT for regex matching)
    There are some modules on PiPy that partially offer XPath 2.0+ functionality.

  2. There are some OSS XML/NoSQL-DBMS that implement XPath/XQuery 2.0 functions, e.g.

    • Zorba, an open source portable embeddable C++ implementation of XQuery 1.0/2.0 which has Python bindings (this question has some pointers),
    • as well as Sedna and some commercial DBMS. Depending on your project, this could be a good choice.
  3. I believe Saxon/C (by Michael Kay) with Cython is the most promising road.
    It was tried before using Boost.Python and at pysaxon.
    Update: A Saxon/C extension for Python 3 has been published meanwhile.

  4. You could use a subprocess to call a CLI XML processor (as suggested here), e.g. subprocess.call(["saxon", "-o:output.xml", "-s:file.xml", "file.xslt"])

  5. Another option is using XSLT/XPath/XQuery with saxon and/or other Java XML classes in Jython.

  6. Finally, you could set-up a web service that does the hard work for you in a language like Java, .NET, etc, that comes with proper XPath 3+ support (also suggested by Kay here).

Still somewhat disappointing, especially for a big language like Python.




回答2:


As mentioned by Martin we have a Saxon product for C/C++/PHP languages, called Saxon/C which out for a few years now. We have been seeing users interested in using Saxon/C with Python. 

One user has successfully used Boost.Python to interface with our C++ library.  Another user has done the interfacing in a different way: https://github.com/ajelenak/pysaxon

We hope to make available an official Saxon/C interface for Python.



来源:https://stackoverflow.com/questions/52707456/evaluate-xpath2-0-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!