Python 解析XML文件
Python文件:
XML文件(sample.xml):
代码如下:
#parsexml.py #本例子参考自python联机文档,做了适当改动和添加 import xml.parsers.expat #控制打印缩进 level = 0 #获取某节点名称及属性值集合 def start_element(name, attrs): global level print ' '*level, 'Start element:', name, attrs level = level + 1 #获取某节点结束名称 def end_element(name): global level level = level - 1 print ' '*level, 'End element:', name #获取某节点中间的值 def char_data(data): if(data == '\n'): return if(data.isspace()): return global level print ' '*level, 'Character data:', data p = xml.parsers.expat.ParserCreate() p.StartElementHandler = start_element p.EndElementHandler = end_element p.CharacterDataHandler = char_data p.returns_unicode = False f = file('sample.xml') p.ParseFile(f) f.close()
XML文件(sample.xml):
代码如下:
<contacts id="bluecrystal"> <item name="keen" fff="ddd"> <telephone type="phone">222222222</telephone> <telephone type="mobile">134567890</telephone> </item> <item name="bcm"> <telephone type="phone">11111111</telephone> <telephone type="mobile">15909878909</telephone> </item> </contacts>
相关推荐
与卿画眉共浮生 2020-10-14
xiyang 2020-08-21
XGQ 2020-07-04
Andrewjdw 2020-05-29
Yakamoz 2020-05-26
行吟阁 2020-05-18
88491874 2020-04-30
baijinswpu 2020-07-29
leonranri 2020-07-26
zhongliwen 2020-07-05
麋鹿麋鹿迷了路 2020-07-05
zengyu00 2020-07-05
CoderBoy 2020-06-28
whbing 2020-06-28
绝望的乐园 2020-06-27
wellfly 2020-06-26
菇星獨行 2020-06-25
草原孤狼 2020-06-25
坚持着执着 2020-06-16