ElementTree find () / findall () cannot find a namespace tag?

Using the following code, I would expect to be able to find the target tag if I specify a 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 find this destination tag?

I tried various implementations of ElementTree, including lxml, where the namespace {*} supposedly accepted. No dice?

+6
source share
1 answer

target not a root element; You must add .// .

 >>> 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>] 
+10
source

All Articles