您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python解析xml模块封装代码

5b51 2022/1/14 8:17:46 python 字数 4296 阅读 349 来源 www.jb51.cc/python

有如下的xml文件: 复制代码代码如下:<?xmlversion=\"1.0\"encoding=\"utf-8\"?>?<root>?<childs>?<childname=\'first\'>1</child>?<childvalue=\"2\">2&l

概述

有如下的xml文件

下面介绍python解析xml文件的几种方法,使用python模块实现。

方式1,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']

方式2,python模块实现获取根节点,按需查找指定节点:

结果:
[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模块封装代码所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶