Changeset 959 for TI07-MOLES/trunk


Ignore:
Timestamp:
19/05/06 06:06:07 (13 years ago)
Author:
lawrence
Message:

Utility to support HTML presentation of vanilla xml (including highlight of
matched search terms) for discovery and browse.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • TI07-MOLES/trunk/StubB/XSLT/browse/portal/cgi/Utilities.py

    r938 r959  
    9393                result+='</%s>'%(elem.tag) 
    9494        return result 
     95         
     96def PrettyPrintHTML(elem,matchList=[]): 
     97    '''Lightweight HTML pretty printing of elementTree elements + highlight 
     98    any words which occur in the element text (and tails) which occur in matchList, 
     99    and formatted using a css something like this: 
     100    === 
     101    DIV.xmlElem {PADDING-LEFT: 20px;} 
     102    .xmlAttrVal {COLOR:Red; } 
     103    .xmlAttrTyp {COLOR:Green; } 
     104    .xmlElemTag {COLOR:Blue; } 
     105.   highlight {BACKGROUND-COLOR:Yellow; } 
     106    === 
     107    ''' 
     108    def span(x,c): return '<span class="%s">%s</span>'%(c,x) 
     109    def div(x,c): return '<div class="%s">%s</div>'%(c,x) 
     110    def match(x):  
     111        if x is None: return '' 
     112        for w in matchList: x=re.sub(w,span(w,'highlight'),x) 
     113        return x 
     114    lt,gt='<b>&lt;</b>','<b>&gt;</b>' 
     115    strAttrib='' 
     116    for att in elem.attrib: 
     117        strAttrib+=' %s="%s"'%(span(att,'xmlAttrTyp'),span(elem.attrib[att],'xmlAttrVal')) 
     118    result='%s%s%s%s%s'%(lt,span(elem.tag,"xmlElemTag"),strAttrib,gt,match(elem.text)) 
     119    children=len(elem) 
     120    if children: 
     121        for item in elem: 
     122            result+=PrettyPrintHTML(item) 
     123        result+='%s%s/%s%s'%(match(item.tail),lt,span(elem.tag,'xmlElemTag'),gt) 
     124    else: 
     125        result+='%s/%s%s'%(lt,span(elem.tag,'xmlElemTag'),gt) 
     126    return div(result,'xmlElem') 
     127 
    95128if __name__=="__main__": 
    96     print cleanup('<abcd&efg>') 
    97     print cleanup('<abcd&amp;efg>') 
     129    x='''<test attr='something'>some content with <a href="target"> display</a> url</test>''' 
     130    import ElementTree as ET 
     131    y=ET.fromstring(x) 
     132    print PrettyPrintHTML(y,['content',]) 
     133    print PrettyPrint(y) 
     134     
Note: See TracChangeset for help on using the changeset viewer.