您的位置:首页 > Web前端 > Node.js

python xml test 遍历element attr textNode

2012-09-28 11:02 597 查看
我的环境是python 2.7.3 on windows

# coding=utf-8

#xml 节点结构可参见D:\Python27\Lib\xml\dom\minidom.py中的继承关系

from xml.dom import minidom

# 工具方法:转node类型为字符串
# tool method: conv node type from int to str
dddict = {1:"ELEMENT_NODE", 2:"ATTRIBUTE_NODE", 3:"TEXT_NODE", 4:"CDATA_SECTION_NODE", 5:"ENTITY_REFERENCE_NODE", 6:"ENTITY_NODE", 7:"PROCESSING_INSTRUCTION_NODE", 8:"COMMENT_NODE", 9:"DOCUMENT_NODE", 10:"DOCUMENT_TYPE_NODE", 11:"DOCUMENT_FRAGMENT_NODE", 12:"NOTATION_NODE"}
def type2str(num):
return dddict.get(num)

# 工具方法:打印一个node
# tool method: print a node(any type)
def print_node(node):
print '--------begin'
print type2str(node.nodeType),
#    if not node.nodeType==node.TEXT_NODE:
#        print node.nodeName
#    if not node.nodeType==node.ELEMENT_NODE:
#        print node.nodeValue
print node.nodeName  #任何TEXT_NODE的name值都应该是"#text", DOCUMENT_NODE #document
print node.nodeValue #任何element的value值都应该是"None"

if node.nodeType==node.DOCUMENT_NODE :
print node.encoding

if node.attributes :
for attr_name, attr_value in node.attributes.items() :
print attr_name, attr_value
print '--------end'

#递归:先打印自己,如果有子节点就遍历所有子节点,否则就是递归退出
#recursion:print a node, if it has childNodes, traversal; else, return.
def print_xml(root):
print_node(root)
if root.hasChildNodes() :
nodes = root.childNodes#class NodeList(list):
for node in nodes :
print_xml(node)

#===========test test=========
#先测一下吧...
#now test it...

#to read
xmldoc = minidom.parse('andy.xml')

# 获取根节点
# get root element: <yydata/>
root = xmldoc.documentElement

# 以"utf-8"的xml格式打印根节点
# print the root element in the "utf-8" xml format
print root.toxml("utf-8")
print '========================'
#print_xml(root)
print_xml(xmldoc)

#附xml文件
'''
<?xml version="1.0" encoding="utf-8"?><yydata myattr1="111" myattr2="2222"><cmd>13</cmd><urlItems><urlItem><id>0</id><url>http://www.baidu.com</url><loadlocal>1</loadlocal></urlItem><urlItem><id>1</id><url>http://www.sina.com.cn</url><loadlocal>0</loadlocal></urlItem></urlItems><pos></pos><notifyItems><notifyItem type="1"><time>15:46</time><notification><txt>快去看看吧~</txt><url>my_matcher_list.jwml</url><fixed>false</fixed></notification></notifyItem><notifyItem type="2"><time>15:46</time><notification><txt>新私信</txt><url>msg_box_stat.jwml</url><fixed>true</fixed></notification></notifyItem></notifyItems></yydata>

'''


s

s
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: