2024-10-01 00:24:40 发布
网友
这样的函数:
getElementDom("root.child.grandchild")
返回grandchild元素
grandchild
是的,它叫做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表达式搜索:
lxml
from xml.etree import ElementTree tree = ElementTree.parse(filename): for element in tree.find('./root/child/grandchild'):
是的,它叫做XPath:
当然,lxml要好得多:
DOM标准中没有这样的函数,不。您可能希望改用^{} library 并使用XPath表达式:
lxml
构建在ElementTree API之上,而不是(古老的)domapi之上。标准库ElementTree API实现也支持有限的XPath表达式搜索:相关问题 更多 >
编程相关推荐