导读
利用Python中自带的标准库xml
解析:importxml.etree.ElementTree
生成:fromxml.dom.minidomimportDocument
处理XML
●测试数据
xmltest.xml:
?xmlversion="1.0"encoding="utf-8"?datastitle="root"dataid="1"name喜马高/nameage18/agegender男/gender/datadataid="2"name喜马妞/nameage28/agegender女/gender/data/datas
●获取/读入
importxml.etree.ElementTreeasetxml_obj=et.ElementTree(file="xmltest.xml")xml_objxml.etree.ElementTree.ElementTreeobjectat0x11f86a
●元素访问
root=xml_obj.getroot()#获取根元素,也是个Element对象root.tag#获取根元素标签datasroot.attrib#获取根元素属性{title:root}forchild_of_rootinroot:#遍历访问其子元素print(child_of_root.tag,child_of_root.attrib)data{id:1}data{id:2}root[0].tag,root[0].attrib#索引访问(data,{id:1})datas=root.findall("data")#获取所有的data标签fordataindatas:#循环访问data标签子元素print(data.find("name").text)喜马高喜马妞datas[0].find("name").text#索引访问data标签的子元素喜马高datas[1].find("name").text喜马妞
●生成/写入
fromxml.dom.minidomimportDocument#初始化一个Documentdoc=Document()#创建两个标签root=doc.createElement("root")head=doc.createElement("head")doc.appendChild(root)#将root标签作为根标签root.appendChild(head)#将head标签添加到root标签作为其子元素#添加数据code=doc.createElement("code")#创建code标签code_text=doc.createTextNode("1")#创建文本数据code.appendChild(code_text)#将code_text文本数据添加到code标签head.appendChild(code)#将code标签添加到head标签下msg=doc.createElement("msg")msg_text=doc.createTextNode("成功!")msg.appendChild(msg_text)head.appendChild(msg)response=doc.createElement("response")response_text=doc.createTextNode("{}")response.appendChild(response_text)head.appendChild(response)#生成xmldoc_xml=doc.toxml(encoding="UTF-8")#写入xmlf=open("text.xml","w+")f.write(doc_xml.decode("UTF-8"))f.close()