• Python读写xml


    python对XML的解析

    常见的XML编程接口有DOM和SAX,这两种接口处理XML文件的方式不同,当然使用场合也不同。

    python有三种方法解析XML,SAX,DOM,以及ElementTree:

    1.SAX (simple API for XML )

    python 标准库包含SAX解析器,SAX用事件驱动模型,通过在解析XML的过程中触发一个个的事件并调用用户定义的回调函数来处理XML文件。

    2.DOM(Document Object Model)

    将XML数据在内存中解析成一个树,通过对树的操作来操作XML。

    3.ElementTree(元素树)

    ElementTree就像一个轻量级的DOM,具有方便友好的API。代码可用性好,速度快,消耗内存少。

    注:因DOM需要将XML数据映射到内存中的树,一是比较慢,二是比较耗内存,而SAX流式读取XML文件,比较快,占用内存少,但需要用户实现回调函数(handler)。

    以上来自:http://www.runoob.com/python/python-xml.html

    其中ElementTree用得多,我在用它生成xml树时成功了,但用生成xml文件时因为树结构中包含中文节点(如下代码中的“中国”二字),导致生成的xm文件中文的部分是乱码,并网上的办法怎么也不能解决。

    import elementtree.ElementTree as ET
    
    country=ET.Element("Country")
    country.set("name",'中国')
    province1=ET.SubElement(country,'province')
    tree=ET.ElementTree(country);
    tree.write(r'C:UsershhxDesktopcountry.xml',encoding='gbk')

    ElementTree的基础官方教程

    import elementtree.ElementTree as ET
    
    # build a tree structure
    root = ET.Element("html")
    
    head = ET.SubElement(root, "head")
    
    title = ET.SubElement(head, "title")
    title.text = "Page Title"
    
    body = ET.SubElement(root, "body")
    body.set("bgcolor", "#ffffff")
    
    body.text = "Hello, World!"
    
    # wrap it in an ElementTree instance, and save as XML
    tree = ET.ElementTree(root)
    tree.write("page.xhtml")

    后来转变思路,用xml.dom.minidom模块来创建xml树形结构并导出xml文件,然后再用ElementTree来读取、解析和查找。

  • 相关阅读:
    一个十分诡异的NullReferenceException异常!
    如何去掉TabControl控件默认添加的TabPage
    GDI+发生一般性错误的解决方法
    C#中各种数组的性能比较
    酷享娱乐新生活
    关于ImageList.Images集合的特殊行为!
    WinForm窗体之间交互的一些方法
    实现单实例应用程序的三种方案
    MySql_Close 释放资源
    数组之List
  • 原文地址:https://www.cnblogs.com/aaronhoo/p/9280772.html
Copyright © 2020-2023  润新知