如果我指定命名空间,使用以下代码我希望能够搜索目标标记.
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,据称可以接受{*}命名空间.没有骰子?
解决方法
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>]