在ElementTree 的“find”和“findall”方法中忽略XML 命名空間
使用ElementTree 模組解析和定位XML 文件中的元素時,命名空間會帶來複雜性。以下介紹如何在 Python 中使用「find」和「findall」方法時忽略命名空間。
當 XML 文件包含命名空間時,會導致 ElementTree 模組在搜尋標籤時考慮它們,就會出現問題。這可能會導致意外結果,如問題中提供的範例所示:
el1 = tree.findall("DEAL_LEVEL/PAID_OFF") # Return None
el2 = tree.findall("{http://www.test.com}DEAL_LEVEL/{http://www.test.com}PAID_OFF") # Return element
要忽略命名空間,解決方法是在使用「find」或「findall」方法之前修改已解析的XML文件中的標籤。這可以使用 ElementTree 的 iterparse() 方法來實作:
import io
from xml.etree import ElementTree as ET
# Parse the XML document
it = ET.iterparse(StringIO(xml))
# Iterate over each element and strip the namespace if present
for _, el in it:
_, _, el.tag = el.tag.rpartition("}") # strip ns
# Get the modified root element
root = it.root
# Now, you can search for elements without namespaces
el3 = root.findall("DEAL_LEVEL/PAID_OFF") # Return matching elements
這個解決方案修改了解析文件中的標籤,使得更容易定位元素,而不需要手動為每個標籤指定命名空間前綴。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3