Python创建xml文件示例

yipeiwu_com5年前Python基础

本文实例讲述了Python创建xml文件的方法。分享给大家供大家参考,具体如下:

这是一个使用ElementTree有关类库,生成xml文件的例子

# *-* coding=utf-8
from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import Element
from xml.etree.ElementTree import SubElement
from xml.etree.ElementTree import dump
from xml.etree.ElementTree import Comment
from xml.etree.ElementTree import tostring
import os
filename="book.xml"
def CreateXml():
  book =ElementTree()
  purOrder =Element("PurchaseOrder")
  book._setroot(purOrder)
  list = Element("account",{'idsn':'2390094'})
  purOrder.append(list)
  item = Element("item1",{"sku":"abcd","qty":"4"})
  SubElement(item,"Name").text="Potato Smasher"
  SubElement(item,"Description").text="Smash Potatoes like never before"
  purOrder.append(item)
  item = Element("item2",{"sku":"gfhi","qty":"40"})
  SubElement(item,"Name").text="Beijing"
  SubElement(item,"Description").text="My Country"
  purOrder.append(item)
  indent(purOrder)
  return book
def indent(elem,level=0):
  i ="\n"+level*"  "
  print elem;
  if len(elem):
    if not elem.text or not elem.text.strip():
      elem.text = i + "  "
    for e in elem:
      print e
      indent(e,level+1)
    if not e.tail or not e.tail.strip():
      e.tail =i
  if level and (not elem.tail or not elem.tail.strip()):
    elem.tail =i
  return elem
if __name__ == '__main__':
  book =CreateXml()
  book.write(filename,"utf-8")
  #book.write("book2.xml","utf-8",True) #true is with xml declaration

PS:这里再为大家提供几款关于xml操作的在线工具供大家参考使用:

在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson

在线格式化XML/在线压缩XML
http://tools.jb51.net/code/xmlformat

XML在线压缩/格式化工具:
http://tools.jb51.net/code/xml_format_compress

XML代码在线格式化美化工具:
http://tools.jb51.net/code/xmlcodeformat

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python操作xml数据技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python中的命令行参数解析工具之docopt详解

前言 docopt 是一个开源的库,代码地址:https://github.com/docopt/docopt。它在 README 中就已经做了详细的介绍,并且还附带了很多例子可供学习,...

使用python批量读取word文档并整理关键信息到excel表格的实例

使用python批量读取word文档并整理关键信息到excel表格的实例

目标 最近实验室里成立了一个计算机兴趣小组 倡议大家多把自己解决问题的经验记录并分享 就像在CSDN写博客一样 虽然刚刚起步 但考虑到后面此类经验记录的资料会越来越多 所以一开始就要做好...

Python的高阶函数用法实例分析

本文实例讲述了Python的高阶函数用法。分享给大家供大家参考,具体如下: 高阶函数 1.MapReduce MapReduce主要应用于分布式中。 大数据实际上是在15年下半年开始火起...

Python随机数random模块使用指南

random 模块是Python自带的模块,除了生成最简单的随机数以外,还有很多功能。 random.random() 用来生成一个0~1之间的随机浮点数,范围[0,10 >...

详解使用 pyenv 管理多个版本 python 环境

 随着同时开发的项目越来越多,需要不停的在各个不同版本的 python 环境之间切换,所以想到了pyenv。以前一直使用的 virtualenv只能管理同一个 python 版...