source: TI07-MOLES/trunk/PythonCode/browse/portal/cgi/browse/ETxmlView.py @ 1577

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI07-MOLES/trunk/PythonCode/browse/portal/cgi/browse/ETxmlView.py@1577
Revision 1577, 5.5 KB checked in by lawrence, 13 years ago (diff)

Browse now modified to use Matt's backend ...

Line 
1# Copyright Bryan Lawrence, Rutherford Appleton Laboratory, CCLRC, 2006
2#
3# This code is made available under the GPL, if you don't know what
4# that means, you have no rights to copy it or use it!
5#
6# Code to support xml and elementTree viewing as text and html
7
8try: #python 2.5
9    import xml.etree.ElementTree as ET
10except:
11    import ElementTree as ET
12import re
13from sub_orphan import *
14
15class nsdumb:
16    ''' provides an xpath interface to element tree nodes which
17    is namespace agnostic '''
18    def __init__(self,root=None):
19        ''' Provide a root element with namespace definitions when
20        instantiatin '''
21        if root is None: 
22            self.xmlns=''
23            return
24        ns=['xmlns','{http://www.w3.org/2001/XMLSchema-instance}schemaLocation']
25        for i in ns: 
26            if i in root.keys():
27                self.xmlns='{%s}'%root.attrib[i].split(' ')[0]
28                break
29            else:
30                self.xmlns=''
31    def __str__(self):
32        return 'Element Tree namespace helper with namespace: [%s]'%self.xmlns
33    def getText(self,elem,xpathExpression,multiple=0):
34        ''' Get a text object sensibly '''
35        if multiple:
36                r=elem.findall(self.xmlns+xpathExpression)
37        else:
38                r=[elem.find(self.xmlns+xpathExpression),]
39        try:  # if element is None, this should fail ...
40                rr=[]
41                for i in r:
42                    t=i.text
43                    if t is not None: 
44                        rr.append(t)
45                    else: rr.append('')
46        except:
47                rr=['',]
48        if multiple: 
49                return rr
50        else: return rr[0] 
51       
52    def find(self,elem,xpathExpression):
53       ''' Return relevant subelement '''
54       xe=self.xmlns+xpathExpression
55       return elem.find(xe)
56   
57    def findall(self,elem,xpathExpression):
58       ''' Return all relevant subelements '''
59       xe=self.xmlns+xpathExpression
60       return elem.findall(xe)
61
62    def strip(self,tag):
63        ''' Given a tag, strip the default namespace '''
64        return tag.lstrip(self.xmlns)
65
66def et2text(elem,indent='',html=0,space='   ',helper=None):
67        '''Lightweight pretty printing of elementTree elements'''
68        def estrip(elem):
69                ''' Just want to get rid of unwanted whitespace '''
70                if elem is None:
71                        return ''
72                else:
73                        return elem.strip()
74        ns=helper
75        if ns is None: ns=nsdumb(elem)
76        strAttrib=''
77        for att in elem.attrib:
78                strAttrib+=' %s="%s"'%(att,elem.attrib[att])
79        result='%s<%s%s>%s'%(indent,ns.strip(elem.tag),strAttrib,estrip(elem.text))
80        children=len(elem)
81        if children:
82                for item in elem:
83                        result+='\n'+et2text(item,indent=indent+space,helper=ns)
84                result+='\n%s%s</%s>'%(indent,estrip(item.tail),ns.strip(elem.tag))
85        else:
86                result+='</%s>'%(ns.strip(elem.tag))
87        return result
88
89
90def et2html(elem,matchList=[],number=0,helper=None):
91    #this method is NDG code ... copyright CCLRC ...
92    '''Lightweight HTML pretty printing of elementTree elements + highlight
93    any words which occur in the element text (and tails) which occur in matchList,
94    and formatted using a css something like this:
95    ===
96    DIV.xmlElem {PADDING-LEFT: 20px;}
97    .xmlAttrVal {COLOR:Red; }
98    .xmlAttrTyp {COLOR:Green; }
99    .xmlElemTag {COLOR:Blue; }
100.   highlight {BACKGROUND-COLOR:Yellow; }
101    ===
102    Line number is not yet implemented.
103    '''
104    def span(x,c): return '<span class="%s">%s</span>'%(c,x)
105    def div(x,c): return '<div class="%s">%s</div>'%(c,x)
106    def match(x): 
107        if x is None: return ''
108        for w in matchList: x=re.sub(w,span(w,'highlight'),x)
109        return x
110    lt,gt='<b>&lt;</b>','<b>&gt;</b>'
111    ns=helper
112    if ns is None: ns=nsdumb(elem) 
113    strAttrib=''
114    for att in elem.attrib:
115        strAttrib+=' %s="%s"'%(span(att,'xmlAttrTyp'),span(elem.attrib[att],'xmlAttrVal'))
116    result='%s%s%s%s%s'%(lt,span(ns.strip(elem.tag),"xmlElemTag"),strAttrib,gt,match(elem.text))
117    children=len(elem)
118    if children:
119        for item in elem:
120            result+=et2html(item,matchList,helper=ns)
121        result+='%s%s/%s%s'%(match(item.tail),lt,span(ns.strip(elem.tag),'xmlElemTag'),gt)
122    else:
123        result+='%s/%s%s'%(lt,span(ns.strip(elem.tag),'xmlElemTag'),gt)
124    return div(result,'xmlElem')
125   
126def loadET(inputString):
127    ''' This method returns an elementtree object after some cleaning
128    of the string, essentially a hack to make sure that xml doesn't contain any
129    naughty & characters alone (typically from URL copies), or unescaped orphan
130    < or > signs ... and that the unicode has been processed to something that
131    might work'''
132     
133    if inputString is None: return None
134    inputString=re.sub(r'&(?!\w+;)', '&amp;', inputString)
135 
136    # first just try and do it so we don't waste time if we don't need to ...
137    try:
138        elem=ET.fromstring(inputString)
139        return elem
140    except:
141        pass
142        # and carry on
143
144    #ok, let's deal with orphan > and < signs then ...
145    subtool=subAI()
146    s=subtool.sub(inputString)
147
148    #now let's sort out an encoding
149    encodings=['utf-8','latin-1','iso-8859-1','ascii',]
150    elem=None
151    for option in encodings:
152        try:
153            s=s.encode(option,'replace')
154            try:
155                elem=ET.fromstring(s)
156            except:
157                s=re.sub('\n','<br/>LINE: ',s)
158                print '<p>%s</p>'%s
159                raise
160        except UnicodeError:
161            pass
162        else:
163            break
164    return elem
165
166def xml2text(xmlString):
167    tree=loadET(xmlString)
168    return et2text(tree)
169
170def xml2HTML(xmlString,**kw):
171    tree=loadET(xmlString)
172    return et2HTML(tree,**kw)
Note: See TracBrowser for help on using the repository browser.