为什么xpath不匹配此ElementTree中的任何内容

2024-10-04 03:25:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图阅读此XML的部分内容,但不理解为什么我的xpath表达式与任何内容都不匹配

s = """
<udhr iso639-3='ada' xml:lang='ada' key='ada' n='Dangme' dir='ltr' iso15924='Latn' xmlns="http://www.unhchr.ch/udhr">
   <title>JE TSUO BLƆ NYA TOMI KƐ HA ADESA HE BLƆHI</title>
   <preamble>
      <title>NYA TSƆƆMI</title>
      <para>Be abɔ nɛ a le odehe si himi nɛ Mawu bɔ adesahi tsuo nɛ a hi si ngɛ je mi, nɛ e ha nɔ tsuaa nɔ he blɔhi sɔsɔɛ, nɛ nɔ ko be he blɔ nɛ e kpɔɔ ngɛ a dɛ ɔ, e ji he jɔmi kɛ dami same yemi kɛ tue mi jɔmi a sipoku ngɛ je mi.</para>
    </preamble>
</udhr>
"""

import xml.etree.ElementTree as ET
tree = ET.fromstring(s)
print(list(tree))
# [<Element '{http://www.unhchr.ch/udhr}title' at 0x10dbf0050>, <Element '{http://www.unhchr.ch/udhr}preamble' at 0x10dbf0110>]
print(tree.findall("title"))
# []
print(tree.findall(".//preamble"))
# []

元素在那里,但是应用任何findxpath表达式都是空的。我错过了什么明显的东西


现在我在根上找到了名称空间xmlns="http://www.unhchr.ch/udhr"声明,当我显式使用时:

print(tree.findall("{http://www.unhchr.ch/udhr}title"))

它确实找到了元素,但是如何更普遍地使用这个名称空间?我试过玩.findall(el, namespaces)dicts,但不知道如何让它工作。毕竟我所有的元素都没有前缀


Tags: treehttp元素titlewwwchnghe