易截截图软件、单文件、免安装、纯绿色、仅160KB

在python中处理XML总结

本文总结了在Python中主要的几种处理XML的方法:
Element Tree
SAX
Dom
使用第三方类库如Amara 2.x, libxml2dom 等
Element Tree
Element Tree是Python 2.5引入的使用简单,快捷的处理方法, 也是Python标准类库推荐的处理XML的方法。
它使用树形节点的形式来读写XML。Element Tree是轻量级的DOM, 所以使用方便且耗资源少。
比如有以下XML文件: sample.xml
<?xml version="1.0" encoding="UTF-8"?>
<users>
<user id="001">
<name>John</name>
<age>25</age>
<phone>12345</phone>
</user>
<user id="002">
<name>Bill</name>
<age>30</age>
<phone>54321</phone>
</user>
<user id="003">
<name>Rex</name>
<age>35</age>
<phone>88888</phone>
</user>
</users> 
实例代码如下:
# -*- coding: utf-8 -*-
import sys
from xml.etree import ElementTree as ET
# 打印user节点,格式为tag:text
def printUser(user):
print "\nid:\t%s" % user.attrib.get('id')
for e in user.getchildren():
print "%s:\t%s" % (e.tag, e.text)
if __name__ == '__main__':
xmlFile = 'sample.xml'

# 解析sample.xml
doc = ET.parse(xmlFile)
users = doc.getroot()

# 遍历所有user,打印id和name
for user in users.findall('user'):
print "ID: %s\tName: %s" % (user.attrib['id'], user.find('name').text)

# 找出id是001的user
user1 = None
for user in users.getiterator('user'):
if user.attrib.get('id') == '001':
user1 = user

# 将user的phone改为999, 再打印这个user节点
if user1 != None:
printUser(user1)
user1.find('phone').text = '9999'
print ET.tostring(user1, 'utf-8')

# 删除name为Rex的user
for user in users.getiterator('user'):
if user.find('name').text == 'Rex':
use


相关文档:

xml出错

 XmlDocument xmlDoc = new XmlDocument();
 xmlDoc.Load(@"E:\大二下\xml\province.xml");
会提示出现以下错误
http://hi.csdn.net/attachment/201005/24/0_1274703276Ld6I.gif
麻烦各位帮忙看看,谢谢了 ......

vc中调用python代码

运行一句python命令
对vc设置路径
include:D:\PYTHON31\INCLUDE
lib:D:\PYTHON31\LIBS
#include "stdafx.h"
#include "python.h"
int main(int argc, char* argv[])
{
 Py_Initialize() ;
 PyRun_SimpleString("print('Hello')");
 //PyRun_SimpleString("print(dir())");
 Py_Finalize();& ......

Python的bug

Python太火了,不学点都感觉自己不是学计算机的,今天看了个不错的《简明python教程》,很不错。不过在学习过程中,居然发现了一个Python的bug,
#!/usr/bin/python
#coding=UTF-8
class Person:
'''Represents a person.'''
population = 0
def __init__(self, name):
'''Initializes the person's data.'''
......

xml特殊字符定义

   XML开发入门基础:XML语法规则(2) - 网页设计专栏 - 编程入门网
     http://www.bianceng.cn/web/XML/200911/11986_2.htm
   
   字符          实体引用
    >   &n ......

XML创建新结点

private void CreateNewXmlNode()
{
String strFileName = string.Empty;
strFileName = this.strCurrentPath + "System.xml";
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(strFileName);
......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号