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
if __name__ == "__main__":
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()
———————————————————————————-
提取struts中配置的action:
import xml.parsers.expat
level = 0
pkg = ”
def start_element(name, attrs):
global level
global pkg
if(name == ‘package’):
pkg = attrs[‘namespace’]
if(name == ‘action’):
print pkg + "/" + attrs[‘name’] + ".action"
#level = level + 1
def end_element(name):
print ”
def char_data(data):
if(data == ‘n’):
return
if(data.isspace()):
return
global level
print ‘ ‘
if __name__ == "__main__":
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()