2013年1月10日 星期四

lxml + python + IPXACT


底下用 lxml xPath 來 parser IPXACT file(.xml). 將來希望能透過 python template 的方式,把UVM寫成個 template file, 之後再用 code gen 的方式把 UVM 的 conf file 跟 register set, parameter set, interface set ...連接起來
from lxml import etree
from StringIO import *
import sys

class Parser:

    _prefixmap = {  'spirit' : 'http://www.spiritconsortium.org/XMLSchema/SPIRIT/1.4',
      'vendorExtensions' : '$UVM_REG_GEN/XMLSchema/SPIRIT',
      'xsi' : 'http://www.w3.org/2001/XMLSchema-instance',
  }

    def __init__(self):
     self._tree  = None

    def __del__(self):
     self._tree  = None

    def open(self, ifile):
     """ open from IP-XACT file and build up etree by lxml """
 try:
     self._ifile = StringIO(open(ifile, 'r').read())
     self._tree  = etree.parse(self._ifile)
     self._ifile.close()
 except IOError as e:
     print "%s not found or build up lxml etree fail" %(ifile)

    def close(self):
     """ close """
 self._tree = None

    def findAll(self, stmt, dtype='text'):
     """ return  list in ['text', 'tag', 'tail', attrib' ]dtype
     return  list in [element ]
     """
 found = filter(lambda i: i !=None, self._tree.xpath(stmt, namespaces=self._prefixmap))
 if dtype == 'text':
     return map(lambda i: i.text, found)
 elif dtype == 'tag':
     return map(lambda i: i.tag, found)
 elif dtype == 'tail':
     return map(lambda i: i.tail, found)
 elif dtype == 'attrib':
     return map(lambda i: i.attrib, found)
 elif dtype == 'obj':
     return found
 else:
     raise valueError("dtype not support %s" %(dtype))


def main():
    pp = Parser()
    pp.open('spi_rgm.spirit')
    print pp.findAll(stmt='/spirit:component/spirit:vendor', dtype='text')
    print pp.findAll(stmt='//spirit:vendor', dtype='text')
    print pp.findAll(stmt='//spirit:vendor', dtype='tag')
    print pp.findAll(stmt='//spirit:vendor', dtype='obj')[0].getparent().tag
    pp.close()
    del pp

if __name__ == '__main__':
    main()

results
>>> ['spiritconsortium.org'] ['spiritconsortium.org'] ['{http://www.spiritconsortium.org/XMLSchema/SPIRIT/1.4}vendor'] {http://www.spiritconsortium.org/XMLSchema/SPIRIT/1.4}component
 download
ref:
http://lxml.de/resolvers.html

沒有留言:

張貼留言