是否有一个函数可以通过元素的DOM地址获取元素



这样的函数:

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'):

最新更新