【问题标题】:ElementTree find()/findall() can't find tag with namespace?ElementTree find()/findall() 找不到带有命名空间的标签?
【发布时间】:2014-01-08 15:05:14
【问题描述】:

如果我指定命名空间,我希望使用以下代码能够搜索目标标记。

import xml.etree.ElementTree as ET

xml = """<?xml version="1.0" encoding="UTF-8"?>
         <xyz2:outer xmlns:xyz1="http://www.company.com/url/common/v1"
                     xmlns:xyz2="http://www.company.com/app/v2"
                     version="9.0"
                     something="false">
             <xyz2:inner>
                 <xyz2:target>
                     <xyz1:idType>name</xyz1:idType>
                     <xyz1:id>A Name Here</xyz1:id>
                 </xyz2:target>
             </xyz2:inner>
         </xyz2:outer>"""

tree = ET.fromstring(xml)

print tree[0][0]
# <Element '{http://www.company.com/app/v2}target' at 0x7f3c294374d0>

tree.find('{http://www.company.com/app/v2}target')
# None

无论我做什么,我都找不到那个目标标签?

我尝试了各种 ElementTree 实现,包括据称接受 {*} 命名空间的 lxml。没有骰子?

【问题讨论】:

    标签: python xml python-2.7 xml-namespaces elementtree


    【解决方案1】:

    target 不是根元素;你应该在前面加上.//

    >>> import xml.etree.ElementTree as ET
    >>> tree = ET.fromstring(xml)
    >>> tree.findall('.//{http://www.company.com/app/v2}target')
    [<Element '{http://www.company.com/app/v2}target' at 0x2d143c8>]
    

    【讨论】:

      猜你喜欢
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-23
      • 1970-01-01
      • 2012-01-26
      • 2023-04-01
      • 2014-03-01
      相关资源
      最近更新 更多