Python 解析XML文件
程序员文章站
2022-05-14 09:06:01
python文件: 复制代码 代码如下:#parsexml.py #本例子参考自python联机文档,做了适当改动和添加 import xml.parsers.expat...
python文件:
#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>
复制代码 代码如下:
#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>