python xml 处理
Posted gaizhongfeng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python xml 处理相关的知识,希望对你有一定的参考价值。
import xml.etree.ElementTree as ET ‘‘‘ xml处理模块 ‘‘‘ from idlelib.IOBinding import encoding tree = ET.parse("xmltest.xml") #获取root root = tree.getroot() print(root) #遍历xml for child in root: print(child.tag,child.attrib) for i in child: print(i.tag,i.text) #只遍历body 节点 for node in root.iter(‘body‘): print(node.tag,node.text) ‘‘‘ 修改 ‘‘‘ for node in root.iter(‘from‘): #修改text node.text="newValue" #修改属性 node.set("test","2") tree.write("xmltest.xml") ‘‘‘ 删除 ‘‘‘ for node in root.findall(‘heading‘): root.remove(node) tree.write("xmltest_delete.xml") ‘‘‘ 创建 ‘‘‘ new_xml = ET.Element("nameList") info= ET.SubElement(new_xml,"info",attrib={"encrypt":"yes"}) name = ET.SubElement(info,"name") age = ET.SubElement(info,"age") age.text= ‘23‘ name.text = "jack" info2 = ET.SubElement(new_xml,"info",attrib={"encrypt":"no"}) age = ET.SubElement(info2,"age") name = ET.SubElement(info2,"name") age.text= ‘25‘ name.text = "flack" et = ET.ElementTree(new_xml) et.write("new_xml.xml",encoding="utf-8",xml_declaration=True) ET.dump(new_xml)
xmltest.xml:
<note> <to>Tove</to> <from test="1">www</from> <heading>Reminder</heading> <heading>adwwwee</heading> <body>Don‘t forget me this weekend!</body> <body>aaaaaaaaaa</body> <body>bbbbbbbbbbb</body> <body> <test>cccccccccc</test> </body> </note>
以上是关于python xml 处理的主要内容,如果未能解决你的问题,请参考以下文章
你如何在 python 中处理 graphql 查询和片段?
在Tomcat的安装目录下conf目录下的server.xml文件中增加一个xml代码片段,该代码片段中每个属性的含义与用途