第一部分:读
########
##
# -*- coding:utf-8 -*-
"""
* User: not me
* Date: 11-11-9
* Time: 13:20
* Desc: not easy for newer like me
""" 
 
from  xml.dom import  minidom
 
 
def get_attrvalue(node, attrname):
     return node.getAttribute(attrname) if node else ''
 
def get_nodevalue(node, index = 0):
    return node.childNodes[index].nodeValue if node else ''
 
def get_xmlnode(node,name):
    return node.getElementsByTagName_r(name) if node else []
 
def xml_to_string(filename='example.xml'):
    doc = minidom.parse(filename)
    return doc.toxml('UTF-8')
 
def get_xml_data(filename='example.xml'):
    doc = minidom.parse(filename) 
    root = doc.documentElement
 
    user_nodes = get_xmlnode(root,'user')
    user_list=[]
    for node in user_nodes: 
        user_id = get_attrvalue(node,'id') 
        node_name = get_xmlnode(node,'username')
        node_email = get_xmlnode(node,'email')
        node_age = get_xmlnode(node,'age')
        node_sex = get_xmlnode(node,'sex')
 
        user_name =get_nodevalue(node_name[0]).encode('utf-8','ignore')
        user_email = get_nodevalue(node_email[0]).encode('utf-8','ignore') 
        user_age = int(get_nodevalue(node_age[0]))
        user_sex = get_nodevalue(node_sex[0]).encode('utf-8','ignore') 
        user = {}
        user['id'] , user['username'] , user['email'] , user['age'] , user['sex'] = (
            int(user_id), user_name , user_email , user_age , user_sex
        )
        user_list.append(user)
    return user_list
 
def test_xmltostring():
    print xml_to_string()
 
def test_laod_xml():
    user_list = get_xml_data()
    for user in user_list :
        #print user['sex']
        print '-----------------------------------------------------'
        if user:
            user_str='编   号:%d\n用户名:%s\n性   别:%s\n年   龄:%s\n邮   箱:%s\n ' % (int(user['id']) , user['username'], user['sex'] , user['age'] , user['email'])
            print user_str
            print '====================================================='
 
if __name__ == "__main__":
    test_xmltostring()
    test_laod_xml()
##code end
############
doc=minidom.parse('example.xml')
root=doc.documentElement
root.getElementsByTagName_r('user')[0].getAttribute('id')
obtain the id attribute
<user id="1000001">
root.getElementsByTagName_r('user')[0].getElementsByTagName_r('username')[0].chileNodes[0].nodeValue
get nodevalue not attribute
<username>Admin</username>
creatDocument()方法可以创建一个指定类型的XML文档对象
##note section
##############
<?xml version="1.0" encoding="UTF-8" ?>
<users>
    <user id="1000001">
        <username>Admin</username>
        <email>admin@live.cn</email>
        <age>23</age>
        <sex>男</sex>
    </user>
</users>
##exampl.xml
###############
第二部分:写
from xml.dom import minidom, Node 
doc = minidom.Document() 
doc.a(doc.createComment("Simple xml document__chapter 8")) 
#generate the book 
#<book> (root node)
book = doc.createElement_x_x('book') 
doc.a(book) 
#the title 
#<title> 
#      sample xml thing 
#</title> 
title = doc.createElement_x_x('title') 
title.a(doc.createTextNode("sample xml thing")) 
book.a(title) #在title在book下
任何级别的元素都有doc.creatElement('string')产生,但由自己的上级node执行
 
#the author section 
<book> 
    <title> 
        sample xml thing 
    </title> 
    <author> 
        <name> 
            <first> 
                ma 
            </first> 
            <last> 
                xiaoju 
            </last> 
        </name> 
author = doc.createElement_x("author") 
book.a(author) 
name = doc.createElement_x('name') 
author.a(name) 
firstname = doc.createElement_x('first') 
firstname.a(doc.createTextNode("ma")) 
name.a(firstname) 
lastname = doc.createElement_x('last') 
name.a(lastname) 
lastname.a(doc.createTextNode("xiaoju")) 

Python xml的更多相关文章

  1. Python XML解析(转载)

    Python XML解析 什么是XML? XML 指可扩展标记语言(eXtensible Markup Language). 你可以通过本站学习XML教程 XML 被设计用来传输和存储数据. XML是 ...

  2. Python xml 模块

    Python xml 模块 TOC 什么是xml? xml和json的区别 xml现今的应用 xml的解析方式 xml.etree.ElementTree SAX(xml.parsers.expat) ...

  3. Python XML解析之ElementTree

    参考网址: http://www.runoob.com/python/python-xml.html https://docs.python.org/2/library/xml.etree.eleme ...

  4. python大法好——Python XML解析

    Python XML解析 什么是XML? XML 被设计用来传输和存储数据. XML是一套定义语义标记的规则,这些标记将文档分成许多部件并对这些部件加以标识. 它也是元标记语言,即定义了用于定义其他与 ...

  5. 【Python】Python XML 读写

    class ACTIVE_FILE_PROTECT_RULE_VIEW(APIView): renderer_classes = (JSONRenderer, BrowsableAPIRenderer ...

  6. python xml.etree ElementTree解析 编辑 xml

    python有很多种xml解析方式,不过感觉etree的ElementTree 用起来最方便. #coding=utf-8 from xml.etree import ElementTree impo ...

  7. python - XML文件及其操作

    xml文件也是实现不同语言或者程序之间进行数据交换的协议,它的特点是尖括号开头,尖括号结尾.使用范围就更为广泛了,tomcat resin kvm 等等,使用了大量的xml文件来进行相关配置.先来看一 ...

  8. Python: xml转json

    1,引言 GooSeeker早在9年前就开始了Semantic Web领域的产品化,MS谋数台和DS打数机是其中两个产品.对web内容做结构化转换和语义处理的主要路线是 XML -> RDF - ...

  9. 【转】python XML 操作总结(创建、保存和删除,支持utf-8和gb2312)

    原文地址:http://hi.baidu.com/tbjmnvbagkfgike/item/6743ab10af43bb24f6625cc5 最近写程序需要用到xml操作,看了看python.org上 ...

  10. python xml.dom模块解析xml

    1. 什么是xml?有何特征? xml即可扩展标记语言,它可以用来标记数据.定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言. 例子:del.xml <?xml version=&q ...

随机推荐

  1. linux使脚本在后台运行

    一.为什么要使程序在后台执行 我们计算的程序都是周期很长的,通常要几个小时甚至一个星期.我们用的环境是用putty远程连接到日本Linux服务器.所以使程序在后台跑有以下三个好处: 1:我们这边是否关 ...

  2. 实现ScrollView中包含ListView,动态设置ListView的高度

    ScrollView 中包含 ListView 的问题 : ScrollView和ListView会冲突,会导致ListView显示不全 <?xml version="1.0" ...

  3. xml提取

    $url = 'http://221.232.141.108/hsdcw/news.xml'; $opts = array( 'http'=>array( 'method'=>" ...

  4. 透明、圆角、阴影效果、背景色渐变、<a></a>去外层虚线、!!!表格标签<table>

    表格标签 <table> 代表表格 width:指表格的宽度           一种是像素 (浏览器缩小的时候出现滚动条)           一种是百分比(跟着浏览器的大小而大小) b ...

  5. ImageX用来做Windows OEM部署

    https://technet.microsoft.com/en-us/library/cc722145(v=ws.10).aspx http://download.csdn.net/user/phc ...

  6. zepto源码--filtered, contains,funcArg,setAttribute,className,deserializeVale--学习笔记

    几个方法 1.filtered 目标是对节点按照一定的选择器进行过滤. 如果传入了过滤选择器,则在nodes节点下,选择符合选择器的节点: 如果没有传入选择器,则返回节点本身,转化为zepto节点. ...

  7. LeetCode -- Triangle 路径求最小和( 动态规划问题)

    Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent n ...

  8. 史上最用心的iOS App上架流程【转】

    转:http://www.jianshu.com/p/16fa56eacb5e 题记 麻痹起来嗨!看网上那么多的教程,依然在我心爱的爱屁屁在上架的时候遇到各种 J8 问题,最大的问题就是:Xcode ...

  9. Java学习-015-CSV 文件写入实例源代码

    在日常的自动化测试脚本编写的过程中,有时要将获取的测试结果或者测试数据存放在数据文件中,以用作后续的参数化测试.常用的文件文件类型无非 txt.csv.xls.properties.xml 这五种文件 ...

  10. Quartz的配置文件quartz.properties详解

    配置 quartz.properties 文件 文件 quartz.properties 定义了 Quartz 应用运行时行为,还包含了许多能控制 Quartz 运转的属性.这个文件应该放在class ...