Python 快捷读写XML的方式


其实 python很多解析XML的包,xml.dom, xml.sax, lxml, 但使用起来不是那么友好。我最喜欢的访问节点方式是a.a1.a2.a3 点,通过 tag一层一层的能访问到自己所需要元素。像java的dom4j,是个非常好的访问方式,直观。所以我想自己实现一个这种方式,但google一下,发现有人已经实现了, xmltodict



解析XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<catalog>
    <maxid>4</maxid>
    <login username="pytest" passwd='123456'>
        <caption>Python</caption>
        <item id="4">
            <caption>测试</caption>
        </item>
    </login>
    <item id="2">
        <caption>Zope</caption>
    </item>
</catalog>



#!/usr/bin/env python
#coding=utf-8

import xmltodict,json

def parse_xml(xml_file):
    xml=open(xml_file,"r")
    xml_string=xml.read()
    xml.close()
    return xmltodict.parse(xml_string)


test=parse_xml("../../conf/test.xml")
print json.dumps(test)
print test["catalog"]["login"]["@username"]
print test["catalog"]["item"]["@id"]
print test["catalog"]["login"]["item"]["caption"]


输入结果:

{"catalog": {"maxid": "4", "login": {"@username": "pytest", "@passwd": "123456", "caption": "Python", "item": {"@id": "4", "caption": "\u6d4b\u8bd5"}}, "item": {"@id": "2", "caption": "Zope"}}}
pytest
2
测试

是不是炒鸡方便直观。


写XML 文件:

#!/usr/bin/env python
#coding=utf-8

import xmltodict,json


def write_xml(xml_dic):
    xml_string=xmltodict.unparse(xml_dic, pretty=True)
    out_xml=open("../../conf/sys_test.xml","w")
    out_xml.write(xml_string)
    out_xml.close()




xml_dic={"root":{"case_sleep_time":"120","log_level":"10","title":"Regression Test Report","result_path":{"@color":"red",'#text':'This is a test'}}}
write_xml(xml_dic)

输出的文件:

<?xml version="1.0" encoding="utf-8"?>
<root>
	<result_path color="red">This is a test</result_path>
	<title>Regression Test Report</title>
	<log_level>10</log_level>
	<case_sleep_time>120</case_sleep_time>
</root>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值