python 对xml文件的操作

使用python读取GB2312编码的xml文件

读取utf-8编码

from xml.tree import ElemenTree
tree = ElementTree.parse(file_path)

 读取GB2312编码

from xml.tree import ElemenTree
tree = ElementTree.parse(file_path, parser=ElementTree.XMLParser(encoding='utf-8'))

新建一个XML并写入内容

def create_xml(xml_path):
    doc = xml.dom.minidom.Document()
    root = doc.createElement('root')#新建根节点
    doc.appendChild(root)
    airCount = doc.createElement("airCount")
    airCount.appendChild(doc.createTextNode('设置节点内容'))
    root.appendChild(airCount)#设置为根节点的子节点
    fp = open(xml_path, 'w')
    #写入xml文件并设置xml文件编码
    doc.writexml(fp, indent='\t', addindent='\t', newl='\n', encoding='utf-8')
    fp.close()

 增加一个节点(GB2312编码)

def insert_node(xml_path):
    #GB2312编码xml文件读取方式
    doc_tree = xTree.parse(xml_path, parser=xTree.XMLParser(encoding='utf-8'))
    root = doc_tree.getroot()
    count = xTree.Element('airCount')
    count.text = str('设置节点内容')
    root.append(count)
    #记得指定编码方式,否则就不是GB2312编码了
    doc_tree.write(xml_path, encoding="GB2312")

增加一个节点(其他编码,如utf-8)

def insert_node(xml_path):
    doc_tree = xTree.parse(xml_path)
    root = doc_tree.getroot()
    count = xTree.Element('airCount')
    count.text = str('设置节点内容')
    root.append(count)
    #指定编码方式
    doc_tree.write(xml_path, encoding="utf-8")

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值