这样的函数:
getElementDom("root.child.grandchild")
返回CCD_ 1元素。
是的,它被称为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')
- ElementTree中的XPath支持
- XPath支持
- XML路径语言(XPath)
DOM标准中没有这样的函数,没有。您可能想使用lxml
库,并使用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'):