|
|
2#

楼主 |
发表于 2007-10-5 20:38:13
|
只看该作者

结果:用于报告所有锚点的一个简单的程序将类似于:
清单 1. 基于 DOM 的代码,用于报告所有的锚点
import elementtree.ElementTree
def detail_anchor(element):
if element.tag == "a":
attributes = element.attrib
if "href" in attributes.keys():
print "'%s' is at URL '%s'." % (element.text,
attributes['href'])
if "name" in attributes.keys():
print "'%s' anchors '%s'." % (element.text,
attributes['name'])
def report(element):
detail_anchor(element)
for x in element.getchildren():
report(x)
report(elementtree.ElementTree.parse("draft2.xml").getroot())
使用下面描述的 5.5.1 引用模板,将产生类似如下的输出:
清单 2. 清单 1 中的程序产生的报告
'related developerWorks content' is at 'http://www.ibm.com/developerworks'.
'entire series' is at 'http://www.ibm.com/...'
...
'IBM product evaluation versions' is at 'http://www.ibm.com/...'
如果有一种标准的方法可用来查询 DOM 实例、解压指定元素、属性和标记的信息,那么可带来多大的简化?您自己看吧:
清单 3. 基于 XPath 的与清单 1 等价的代码。
import elementtree.ElementTree
def detail_anchor(element):
if element.tag == "a":
attributes = element.attrib
if "href" in attributes.keys():
print "'%s' is at URL '%s'." % (element.text,
attributes['href'])
if "name" in attributes.keys():
print "'%s' anchors '%s'." % (element.text,
attributes['name'])
for element in \
elementtree.ElementTree.parse("draft2.xml").findall("//a"):
detail_anchor(element)
清注意,“//a” 在英语中的意思是 “在整个文档中搜索标记为 ‘a’ 的元素”。从本质上说,清单 3 产生的输出与 清单 2 的输出是相同的。 |
|