Python XML模块基础用法指南
本文介绍Python中处理XML数据的基础方法。通过xml.etree.ElementTree模块,可以实现对XML文件的解析、遍历、修改节点属性与文本、删除节点以及动态创建新的XML文档结构。内容涵盖基本语法示例及常见操作代码,适用于需要与旧系统接口进行数据交换的场景。
一、XML简介
XML是一种用于在不同编程语言或应用程序之间交换数据的协议格式。虽然JSON在现代开发中更为简洁易用,但在JSON尚未普及的历史时期,XML是主流选择。目前,许多传统行业(如金融领域)的系统接口仍主要依赖XML进行数据交互。
XML的基本格式通过尖括号< >定义的节点来区分数据结构,形成层级化的文档树。
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank updated="yes">69</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
二、Python中操作XML
XML协议在多种编程语言中均得到支持。在Python中,可以使用内置的xml模块来执行XML相关的操作。
# print(root.iter('year')) #全文搜索
# print(root.find('country')) #在root的子节点找,只找一个
# print(root.findall('country')) #在root的子节点找,找所有
import xml.etree.ElementTree as ET
tree = ET.parse("xmltest.xml")
root = tree.getroot()
print(root.tag)
#遍历xml文档
for child in root:
print('========>', child.tag, child.attrib, child.attrib['name'])
for i in child:
print(i.tag, i.attrib, i.text)
#只遍历year 节点
for node in root.iter('year'):
print(node.tag, node.text)
#---------------------------------------
import xml.etree.ElementTree as ET
tree = ET.parse("xmltest.xml")
root = tree.getroot()
#修改
for node in root.iter('year'):
new_year = int(node.text) + 1
node.text = str(new_year)
node.set('updated', 'yes')
node.set('version', '1.0')
tree.write('test.xml')
#删除node
for country in root.findall('country'):
rank = int(country.find('rank').text)
if rank > 50:
root.remove(country)
tree.write('output.xml')
#在country内添加(append)节点year2
import xml.etree.ElementTree as ET
tree = ET.parse("a.xml")
root = tree.getroot()
for country in root.findall('country'):
for year in country.findall('year'):
if int(year.text) > 2000:
year2 = ET.Element('year2')
year2.text = '新年'
year2.attrib = {'update': 'yes'}
country.append(year2) #往country节点下添加子节点
tree.write('a.xml.swap')
三、手动创建XML文档
import xml.etree.ElementTree as ET
new_xml = ET.Element("namelist")
name = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"})
age = ET.SubElement(name, "age", attrib={"checked": "no"})
sex = ET.SubElement(name, "sex")
sex.text = '33'
name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"})
age = ET.SubElement(name2, "age")
age.text = '19'
et = ET.ElementTree(new_xml) #生成文档对象
et.write("test.xml", encoding="utf-8", xml_declaration=True)
ET.dump(new_xml) #打印生成的格式
以上是关于Python XML模块基础使用的介绍,更多详细资料请参考本站其他相关文章。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













