python 写xml_Python对XML读写

介绍

由于Python对XML读写有多种库,本文以xml.etree import ElementTree为例。

解析

from xml.etree import ElementTree as ET

############ 解析方式一 ############

# 打开文件,读取XML内容

str_xml = open('xo.xml', 'r').read()

# 利用ElementTree.XML将字符串解析成xml对象,root代指xml文件的根节点

root = ET.XML(str_xml)

操作XML

XML遍历

from xml.etree import ElementTree as ET

############ 解析方式二 ############

# 直接解析xml文件

tree = ET.parse("xo.xml")

# 获取xml文件的根节点

root = tree.getroot()

### 操作

# 顶层标签

print(root.tag)

# 遍历XML文档的第二层

for child in root:

# 第二层节点的标签名称和标签属性

print(child.tag, child.attrib)

# 遍历XML文档的第三层

for i in child:

# 第二层节点的标签名称和内容

print(i.tag,i.text)

# 遍历XML中所有的year节点

for node in root.iter('year'):

# 节点的标签名称和内容

print(node.tag, node.text)

#修改:将year节点中的内容自增一

new_year = int(node.text) + 1

node.text = str(new_year)

# 设置属性

node.set('name', 'alex')

node.set('age', '18')

# 删除属性

del node.attrib['name']

# 遍历data下的所有country节点

for country in root.findall('country'):

# 获取每一个country节点下rank节点的内容

rank = int(country.find('rank').text)

if rank > 50:

# 删除指定country节点

root.remove(country)

############ 保存文件 ############

tree = ET.ElementTree(root)

tree.write("new.xml", encoding='utf-8')

## 可能需要的调整格式

from xml.dom import minidom

def xmlwrite(root,filepath)

rough_string = ET.tostring(root, 'utf-8')

reparsed = minidom.parseString(rough_string)

raw_str = reparsed.toprettyxml(indent='',newl="")

output = open(filepath,'w+',encoding='utf-8')

output.write('<?xml version="1.0" encoding="UTF-8"?> \n ')

output.write(raw_str)

output.close()

http://www.cnblogs.com/lijinrui/p/5619360.html

每个节点都具有以上方法,通过root可以操作整个xml文件。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值