利用python的xmllib2实现XML文件解析
2012-08-19 20:37
1236 查看
http://www.fjqnl.net/?p=126
待解析的XML文件:
<?xml version='1.0'?><people class="dgdg"><person class="dfdg"><![CDATA[here is a bunch of fun text that i want to get a substring out of.]]><name class="DEV" col="dark"><![CDATA[function matchwo(a,b){if(a < b && a < 0)then{return 1;}else{return 0;}}]]></name><age class="ddg">34</age><friends class="hddd"><friend class="helll">Steve</friend><friend class="dgdgdfe">Mark</friend><friend class="dgdga" dgl="dgdgdash">Dave</friend><![CDATA[here is a bunch of fun text that i want to get a substringout of.]]></friends></person></people>用python实现的解析程序:
import libxml2def wlakProperty(xmlnode):'''提取节点属性函数'''if not xmlnode.properties == None:for property in xmlnode.properties: #循环打印节点属性if property.type == 'attribute':print property.name + '=' + property.content,def walkTree(xmlnode):'''遍历节点函数'''child = xmlnode.childrenwhile child is not None: #判断子节点是否存在if not child.isBlankNode(): #判断子节点是否为空元素if child.type == "element":childCount = int(child.xpathEval('count(*)')) #计算字节点素数目depth = int(child.xpathEval('count(ancestor::*)'))-1 #计算此时节点深度,使输出有层次if childCount == 0: #如果没有字节点了,则打印此节点print depth * '\t' + child.name + ':' + child.content,wlakProperty(child)print '\n'else: #依然存在子节点,继续递归遍历print depth * '\t' + child.name,wlakProperty(child)print '\n'walkTree(child)child = child.nextif __name__ == '__main__':doc = libxml2.parseFile("people.xml") #导入要解析的XML文件root = doc.getRootElement()#获取根节点walkTree(root)doc.freeDoc()参考:http://ukchill.com/technology/getting-started-with-libxml2-and-python-part-1/
相关文章推荐
- python 利用lxml 解析xml文件
- Python实现XML文件解析的示例代码
- 个人安卓学习笔记---分别利用SAX、DOM和Pull实现对XML文件的解析并进行单元测试
- 一键解析XML文件(利用Digester实现可配置)
- android应用开发之利用SAX、DOM和Pull实现对XML文件的解析并进行单元测试
- 利用python将xml文件解析成html文件的实现方法
- Python利用正则表达式实现计算器算法思路解析
- python实现XML文件解析与修改
- QT5下vs2013中利用tinyXML解析XML文件
- 【转】Python实现修改Windows CMD命令行输出颜色(完全解析)
- js解析xml文件并实现省市的二级连动分析案例
- 利用AJAX解析XML文件并且用 DOM呈现
- Python 利用 XSD 文件,解析 XML 文件
- python利用inotify实现把nginx日志实时写入数据库
- 利用Caffe+Python实现Kaggle上Digit Recognition练手项目
- 利用python收发邮件功能实现远程电脑的控制
- 利用Python解析CSV文件
- 私有云方案——利用阿里云云解析实现DDNS
- 利用python模拟实现POST请求提交图片的方法
- 利用Python实现Fibonacci序列算法的三种方法