其实 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>