首頁  >  文章  >  後端開發  >  如何在 Python ElementTree 中忽略元素位置的 XML 命名空間?

如何在 Python ElementTree 中忽略元素位置的 XML 命名空間?

Linda Hamilton
Linda Hamilton原創
2024-10-26 07:18:30512瀏覽

How to Ignore XML Namespaces for Element Location in Python ElementTree?

在Python ElementTree 中忽略元素位置的XML 命名空間

在ElementTree 模組中,在遇到以下情況時,在XML 文件中定位特定元素可能具有挑戰性命名空間,如提供的範例所示。使用findall方法時,在每個標籤前包含{http://www.test.com}會變得不方便。

解決方案:

而不是修改對於 XML 文件本身,更優化的方法是在解析 XML 後修改標籤名稱。這允許處理多個命名空間和命名空間別名。

這是使用 iterparse 函數修改的程式碼:

<code class="python">from io import StringIO  # for Python 2 import from StringIO instead
import xml.etree.ElementTree as ET

with open('test.xml', 'r') as f:
    xml = f.read()

it = ET.iterparse(StringIO(xml))
for _, el in it:
    _, _, el.tag = el.tag.rpartition('}')  # strip ns

root = it.root</code>

透過設定 _, _, el.tag = el.tag。 rpartition('}'),命名空間 (_{http://www.test.com}) 從標籤名稱中刪除。這允許對標籤進行後續處理,而無需考慮其名稱空間。因此,findall 方法:

<code class="python">el1 = root.findall("DEAL_LEVEL/PAID_OFF")</code>

將傳回所需的 。不含命名空間前綴的元素。

以上是如何在 Python ElementTree 中忽略元素位置的 XML 命名空間?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn