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

1

10

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?

Sophistication answered 8/1, 2014 at 15:5 Comment(0)
E
19

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>]
Evensong answered 8/1, 2014 at 15:9 Comment(1)
nobody should have to search with a namespace: ElementTree.fromstring(content).iterfind('.//{*}Mytag'))Assembler

© 2022 - 2024 — McMap. All rights reserved.