这样的功能:
getElementDom("root.child.grandchild")
返回grandchild
元素。
答案 0 :(得分:2)
是的,它被称为XPath:
from cStringIO import StringIO
import xml.etree.ElementTree
from xml.etree import ElementTree as ET
doc = StringIO("""
<document>
<title>People working for me</title>
<person xmlns:foaf="http://xmlns.com/foaf/0.1/"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<name>Jim</name>
<title>Porch Light Switcher</title>
<foaf:homepage rdf:resource="http://example.com/his_page" />
</person><person>
<name>Joe</name>
<title>Bottle Washer, 3rd class</title>
<nick xmlns="http://xmlns.com/foaf/0.1/">Joe-Joe</nick>
</person>
</document>
""")
tree = ET.parse(doc)
print tree.findall("person/title")
当然,lxml要好得多:
f = StringIO('<foo><bar></bar></foo>')
tree = etree.parse(f)
r = tree.xpath('/foo/bar')
答案 1 :(得分:1)
DOM标准中没有这样的功能,没有。您可能希望使用lxml
library代替并使用XPath表达式:
from lxml import etree
tree = etree.parse(filename)
for element in tree.xpath('./root/child/grandchild'):
lxml
建立在ElementTree API之上而不是(古老的)DOM API之上。标准库ElementTree API实现也支持有限的XPath表达式搜索:
from xml.etree import ElementTree
tree = ElementTree.parse(filename):
for element in tree.find('./root/child/grandchild'):