python 中minidom解析xml
python 中minidom解析xml
2009年06月26日 星期五 08:40
下面只列出一些常用的方法属性,如果要查看更多的方法, 可以去看文件minidom如何实现的。
获得Document对象
法一:
import xml.dom.minidom as m_dom
doc1 = m_dom.getDOMImplementation().createDocument(None, "root1", None)
doc1.documentElement.toxml(encoding="utf-8")
'<root1/>'
法二:
s = "<node><xxxx/></node>"
doc2 = m_dom.parseString(s)
print doc2.toprettyxml(indent=" ", newl="\n", encoding="utf-8")
<?xml version="1.0" encoding="utf-8"?>
<node>
<xxxx/>
</node>
获得跟节点:
rt = doc1.documentElement
创建节点:
node1 = doc1.createElement("node1")
rt.appendChild(node1)
rt.toxml()
'<root1><node1/></root1>'
设置/获得属性:
node1.setAttribute("name", "name1")
rt.toxml()
'<root1><node1 name="name1"/></root1>'
node1.getAttribute("name")
'name1'
创建数据节点:
dt = doc1.createTextNode("the datas.")
node1.appendChild(dt)
rt.toxml()
'<root1><node1 name="name1">the datas.</node1></root1>'
node1.firstChild.toxml()
'the datas.'
获得子节点:
node1
<DOM Element: node1 at 0xed0aa8>
rt.childNodes
[<DOM Element: node1 at 0xed0aa8>]
rt.getElementsByTagName("node1")
[<DOM Element: node1 at 0xed0aa8>]
rt.firstChild
<DOM Element: node1 at 0xed0aa8>
node2 = doc1.createElement("node2")
rt.appendChild(node2)
<DOM Element: node2 at 0xe890a8>
rt.toxml()
'<root1><node1 name="name1">the datas.</node1><node2/></root1>'
rt.childNodes
[<DOM Element: node1 at 0xed0aa8>, <DOM Element: node2 at 0xe890a8>]
node1.firstChild
<DOM Text node "the datas.">
删除子节点:
n2 = rt.childNodes[1]
rt.removeChild(n2)
<DOM Element: node2 at 0xe890a8>
rt.toxml()
'<root1><node1 name="name1">the datas.</node1></root1>'
node1.removeChild(node1.firstChild)
<DOM Text
相关文档:
文件操作是程序设计中不可或缺的重要部分。Python通过一个内置函数open来打开文件。
open(filename,mode,buffer)
其中第一个参数是要打开的文件的文件名,必选;第二个是打开方式,可选;第三个为缓冲区,可选。默认情况下是以“读”模式打开文件。该函数 ......
原文
Python和C分别有着各自的优缺点,用Python开发程序速度快,可靠性高,并且有许多现成模块可供使用,但执行速度相对较慢;C语言则正好相反,其执行速度快,但开发效率低。为了充分利用两种语言各自的优点,比较好的做法是用Python开发整个软件框架,而用C语言实现其关键模块。本文介绍如何利用C语言来扩展Python的功 ......
Python作为一种功能强大且通用的编程语言而广受好评,它具有非常清晰的语法特点,适用于多种操作系统,目前在国际上非常流行,正在得到越来越多的应用。
下面就让我们一起来看看它的强大功能:
Python(派森),它是一个简单的、解释型的、交互式的、可移植的、面向对象的超高级语言。这就是对Python ......
from random import randint #导入随即函数
def guessNum(): &nbs ......
简单加密,用python来写写。
#coding=utf-8
'''
Description: 可逆的加密与解密
Environment: python2.5.x
Author:idehong@gmail.com
'''
import os
import sys
class Code(object):
'''可逆的加密与解密'''
def __init__(self, key = "idehong@gmail.com"):
self.__src_key ......