首先下载lxml, [http://www.lfd.uci.edu/~gohlke/pythonlibs/](http://www.lfd.uci.edu/~gohlke/pythonlibs/) ,然后添加引用
fromlxmlimport_elementpathasDONTUSE
fromlxmlimportetree
具体示例:
**1.添加命名空间**
#set namespace
nsmap = {"xsi":"http://www.w3.org/2001/XMLSchema-instance"}
g_statisticsRoot = etree.Element("DcmStatistics", nsmap = nsmap)
**2.添加xml schema引用**
#add xsd reference
g_statisticsRoot.set("{http://www.w3.org/2001/XMLSchema-instance}noNamespaceSchemaLocation","DcmStatistics.xsd")
**3.添加注释**
#add comment, 利用addprevious添加到根节点的前面
comment = etree.Comment("create by jiangong.li")
g_statisticsRoot.addprevious(comment)
**4.尝试多种编码来解析xml**
defdecodingXml(xmlFile):
tree = None
encoding ="utf-8"
while(True):
try:
parser = etree.XMLParser(remove_blank_text=True, encoding=encoding, remove_comments =False)
tree = etree.parse(xmlFile, parser)
exceptExceptionase:
if(encoding !="gb18030"):
encoding ="gb18030"
continue
else:
print("\nPAR XML ERROR, decoding error.")
break
break
returntree
**5.遍历xml下的所有子节点,不止直属第一级子节点.iter()**
** for**element**in**root.iter():
element.tail=None
**6.遍历xml下的第一级子节点.iterchildren()**
foreinsrcParentNode.iterchildren():
ifeissrcParentNode:
continue
name =""
#statistics node
if e.tag =="element":
name ="Element"
elife.tag =="sequence":
name ="Sequence"
elife.tag =="item":
name ="Item"
else:
print("\nUnsupported element type: %s\n"%(e.tag))
name = e.tag
# Only parse element/sequence/item
continue
**7.添加子节点到尾部. append()**
defgetXmlElement(nodeName, parentNode):
ifparentNode == None:
raiseException("parent node is None")
nodes = parentNode.xpath('./'+nodeName)
iflen(nodes) == 0:
node = etree.Element(nodeName)
parentNode.append(node)
returnnode
else:
returnnodes[0]
**8.格式化成str输出**
etree.tostring(g_statisticsRoot, encoding="UTF-8", xml_declaration=True, pretty_print=True, with_comments=True)
**9.保存成xml文件**
statisticsResult = open(g_xmlName,"bw+")
statisticsResult.write(etree.tostring(g_statisticsRoot, encoding="UTF-8", xml_declaration=True, pretty_print=True, with_comments=True))
statisticsResult.flush()
statisticsResult.close()
- 前言
- PythonPath在Windows 下的设置
- Sublime Text: [Decode error - output not utf-8]
- Python 写文件时的Unicode设置
- python中文件打开的各个标识含义
- python 3中对list进行sort时,返回值为None
- python 3中使用getattr和*args时, 出现传入参数不一致的问题
- import module, from module import funtion区别
- Python 中list, dictionary 与 file相互操作
- 编译Python出现Tab,空格的问题
- Sublime Text2中Evernote 插件的使用
- python中全局变量的使用
- python中string和bool的转换
- python中http的一些编码转换
- python中http请求中添加cookie支持
- python构造一个http请求
- python中如何定义main方法
- python为类定义构造函数
- python中print的几种用法
- 自己写的工具:把Evernote(印象笔记)的笔记导入到博客(Blog)中
- Python打包成exe
- python中lxml的应用