Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 954
Pricey Avatar asked Jan 08 '14 15:01

Pricey


1 Answers

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>]
like image 96
falsetru Avatar answered Oct 16 '22 17:10

falsetru