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>