ElementTree find()/findall() can't find tag with namespace?

10,092

target is not a root element; You should prepend .//.

>>> 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>]
Share:
10,092
Pricey
Author by

Pricey

Red Hat Certified Engineer (RHEL7) Red Hat Certified Engineer (RHEL6) Red Hat Certified Technician (RHEL5)

Updated on June 04, 2022

Comments

  • Pricey
    Pricey almost 2 years

    Using the following code I would expect to be able to search for the target tag, if I specify the namespace.

    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
    

    No matter what I do, I can't manage to find that target tag?

    I've tried various ElementTree implementations including lxml where {*} namespaces are allegedly accepted. No dice?