Python 中的 XPath 實作選項
問題:Python 中有哪些庫用於 XPath 支援?哪個選項提供全面的實施?如何應用這些庫,在哪裡可以訪問它們的網站?
答案:
Libxml2
優點:
缺點:
ElementTree
好處:
好處:
好處:
<code class="python">import libxml2 doc = libxml2.parseFile("tst.xml") ctxt = doc.xpathNewContext() res = ctxt.xpathEval("//*") if len(res) != 2: print("xpath query: wrong node set size") sys.exit(1) if res[0].name != "doc" or res[1].name != "foo": print("xpath query: wrong node set value") sys.exit(1) doc.freeDoc() ctxt.xpathFreeContext()</code>
有限地遵守完整的XPath 規範
<code class="python">from elementtree.ElementTree import ElementTree mydoc = ElementTree(file='tst.xml') for e in mydoc.findall('/foo/bar'): print(e.get('title').text)</code>
範例程式碼:
Libxml2 XPath 範例:
範例:網站參考:Libxml2:https://www.xmlsoft.org/ ElementTree:包含在Python 標準庫中最終,libxml2 和ElementTree 之間的選擇取決於應用程式的特定要求和約束。 Libxml2 為複雜用例提供完整的 XPath 合規性和最佳效能,而 ElementTree 為基本路徑選擇任務提供更簡單、更方便的選項。以上是哪些 Python 函式庫提供 XPath 支援以及如何實現它們?的詳細內容。更多資訊請關注PHP中文網其他相關文章!