有没有函数可以通过元素的DOM地址来获取元素?

2024-10-01 00:24:40 发布

您现在位置:Python中文网/ 问答频道 /正文

这样的函数:

getElementDom("root.child.grandchild")

返回grandchild元素


Tags: 函数child元素rootgrandchildgetelementdom
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')

DOM标准中没有这样的函数,不。您可能希望改用^{} library并使用XPath表达式:

from lxml import etree

tree = etree.parse(filename)
for element in tree.xpath('./root/child/grandchild'):

lxml构建在ElementTree API之上,而不是(古老的)domapi之上。标准库ElementTree API实现也支持有限的XPath表达式搜索:

from xml.etree import ElementTree

tree = ElementTree.parse(filename):
for element in tree.find('./root/child/grandchild'):

相关问题 更多 >