概述
有如下的xml文件:
下面介绍python解析xml文件的几种方法,使用python模块实现。
结果:
[html] view plaincopy
name: root attrs: []
chars
name: childs attrs: []
chars
name: child attrs: [u'name']
chars 1
endname child
chars
name: child attrs: [u'value']
chars 2
endname child
chars
endname childs
chars
endname root
[u'\n',u'\n',u'1',u'2',u'\n']
结果:
[html] view plaincopy
Dom:
<?xml version="1.0" ?><hash>
<request name="first">/2/photos/square/type.xml</request>
<error_code>21301</error_code>
<error>auth faild!</error>
</hash>
root:
<hash>
<request name="first">/2/photos/square/type.xml</request>
<error_code>21301</error_code>
<error>auth faild!</error>
</hash>
<request name="first">/2/photos/square/type.xml</request>
child node attribute name: first
child node name: request
child node len: 1
child data: /2/photos/square/type.xml
=======================================
more help info to see:
两种方法各有其优点,python的xml处理模块太多,目前只用到这2个。
=====补充分割线================
实际工作中发现python的mimidom无法解析其它编码的xml,只能解析utf-8的编码,而其xml文件的头部申明也必须是utf-8,为其它编码会报错误。
网上的解决办法都是替换xml文件头部的编码申明,然后转换编码为utf-8再用minidom解码,实际测试为可行,不过有点累赘的感觉。
本节是 python解析xml模块封装代码 的第二部分。
====写xml内容的分割线=========
以上封装了minidom,支持通过xpath来写节点,不支持xpath带属性的匹配,但支持带索引的匹配。
比如:/root/child[1],表示root的第2个child节点。
总结
以上是编程之家为你收集整理的python解析xml模块封装代码全部内容,希望文章能够帮你解决python解析xml模块封装代码所遇到的程序开发问题。
如果您也喜欢它,动动您的小指点个赞吧