要解析的xml文件(文件名e.xml):
<?xml version="1.0" encoding="ISO-8859-1"?> <bookstore> <book> <title lang="eng">Harry Potter</title> <price>29.99</price> </book> <book> <title lang="eng">Learning XML</title> <price>39.95</price> </book> </bookstore>
python脚本
#!/usr/bin/env python
#coding: utf8
from lxml import etree
from xml.etree import ElementTree
read_file = file('e.xml')
lines = []
for line in read_file:
lines.append(line)
read_file.close()
temp_str = ''.join(lines)
root = etree.XML(temp_str)
nodes = root.xpath("//book/title")
for node in nodes:
print node.tag
结果是:
title
title
更多 内容 参考:
http://www.w3school.com.cn/xpath/
http://lxml.de/
http://www.ibm.com/developerworks/cn/xml/x-hiperfparse/