python xml test 遍历element attr textNode

我的环境是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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值