在学习contents_xml.py 脚本中,发现该脚本使用到optparse lib,我们需要了解optparse的使用。通过网络博客了解到optparse库的使用
然后顺利的学习了简单的xml文件解析脚本
import sys
import optparse
from lxml.etree import ElementTree
class FileNode(object):
def __init__(self, root):
self.root = root
def getAlternative(self, tag, flavor=None):
if flavor:
elem = self.root.find('./%s/[flavor=%s]' % (tag, flavor))
if elem:
return elem.text
elem = self.root.find('./%s' % tag)
if elem is not None:
return elem.text
return None
def getName(self, flavor=None):
return self.getAlternative(tag='file_name', flavor=flavor)
def getPath(self, flavor=None):
return self.getAlternative(tag='file_path', flavor=flavor)
def getFullName(self, flavor=None):
name = self.getName(flavor=flavor)
path = self.getPath(flavor=flavor)
if name == None or path == None:
return None
fullname = path + '/' + name
return fullname.strip()
class ContentsXml(object):
ALL_TAGS = ['download_file', 'file_ref']
def __init__(self, xmlFile=None):
self.tree = ElementTree(file=xmlFile)
self.root = self.tree.getroot()
def findFiles(self, name, tags, attr):
files = list()
if tags == None:
tags == ALL_TAGS
else:
tags = tags.split(',')
if tags == None:
tags = '*'
for tag in tags:
print 'wangxf14 debug tag : ', tag
print 'wangxf14 debug tags : ', tags
xpath = './/' + tag
if attr != None and attr != '':
xpath = xpath + ('/[@%s]' % attr)
print 'wangxf14 debug xpath : ', xpath
for e in self.root.findall(xpath):
#print 'wangxf14 debug e : ', e
node = FileNode(e)
fullname = node.getFullName()
print 'wangxf14 debug fullname : ', fullname
if name == None:
files.append(fullname)
elif fullname.endswith(name):
print 'wangxf14 debug fullname.endswith : ', fullname
files.append(fullname)
return ' '.join(files)
def findFileWithTag(self, name, tag, flavor=None):
files = self.root.findall('.//%s' % tag)
for e in files:
fnode = FileNode(e)
fullname = fnode.getFullName()
if fullname.endswith(name):
return fnode.getFullName()
return None
if __name__ == '__main__':
if sys.argv[1] == 'find':
parser = optparse.OptionParser(usage=
'python contents-xml.py find --name NAME --tags TAG,TAG --attr=ATTR')
group = parser.add_option_group('contents.xml')
group.add_option('-c', '--contents-xml',
dest='contents_xml',
action='store',
help='contents xml')
group = parser.add_option_group('name')
group.add_option('-n', '--name',
dest='name',
action='store',
help='file name for hint')
group = parser.add_option_group('tags')
group.add_option('-t', '--tags',
dest='tags',
action='store',
help='tags')
group = parser.add_option_group('attr')
group.add_option('-a', '--attr',
dest='attr',
action='store',
help='attribute')
opts, args= parser.parse_args(sys.argv[2:])
print 'wangxf14 debug ', opts
xml = ContentsXml(opts.contents_xml)
print xml.findFiles(opts.name, opts.tags, opts.attr)