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基于右递归解决八皇后问题的方法

本文实例讲述了python基于右递归解决八皇后问题的方法。分享给大家供大家参考。具体分析如下: 凡是线性回溯都可以归结为右递归的形式,也即是二叉树,因此对于只要求一个解的问题,采用右递归...

Python request设置HTTPS代理代码解析

之前版本的代理中,可以使用fiddler进行HTTP包的代理,但是代理HTTPS包时,执行错误 self._sslobj.do_handshake() ssl.SSLError:...

用Python实现web端用户登录和注册功能的教程

用Python实现web端用户登录和注册功能的教程

用户管理是绝大部分Web网站都需要解决的问题。用户管理涉及到用户注册和登录。 用户注册相对简单,我们可以先通过API把用户注册这个功能实现了: _RE_MD5 = re.compil...

pandas DataFrame 根据多列的值做判断,生成新的列值实例

pandas DataFrame 根据多列的值做判断,生成新的列值实例

环境:Python3.6.4 + pandas 0.22 主要是DataFrame.apply函数的应用,如果设置axis参数为1则每次函数每次会取出DataFrame的一行来做处理,如...

在windows下快速搭建web.py开发框架方法

在windows下快速搭建web.py开发框架方法

  用Python进行web开发的话有很多框架供选择,比如最出名的Django,tornado等,除了这些框架之外,有一个轻量级的框架使用起来也是非常方便和顺手,就是web.py。它由一...