source: TI02-CSML/trunk/parser/parseTest.py @ 961

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI02-CSML/trunk/parser/parseTest.py@961
Revision 961, 4.3 KB checked in by domlowe, 14 years ago (diff)

Added prettyprintHTML function to cgi parser

Line 
1#!/usr/local/NDG/ActivePython-2.4/bin/python2.4
2
3import cgi
4from cElementTree import *
5from Parser import *
6from xml.dom.minidom import parseString
7import sys
8import parser_extra
9import elementtree.ElementTree as etree
10import traceback
11"""Test for GML/CSML parsing code
12"""
13def PrettyPrintHTML(elem,matchList=[]):
14    '''Lightweight HTML pretty printing of elementTree elements + highlight
15    any words which occur in the element text (and tails) which occur in matchList,
16    and formatted using a css something like this:
17    ===
18    DIV.xmlElem {PADDING-LEFT: 20px;}
19    .xmlAttrVal {COLOR:Red; }
20    .xmlAttrTyp {COLOR:Green; }
21    .xmlElemTag {COLOR:Blue; }
22.   highlight {BACKGROUND-COLOR:Yellow; }
23    ===
24    '''
25    def span(x,c): return '<span class="%s">%s</span>'%(c,x)
26    def div(x,c): return '<div class="%s">%s</div>'%(c,x)
27    def match(x):
28        if x is None: return ''
29        for w in matchList: x=re.sub(w,span(w,'highlight'),x)
30        return x
31    lt,gt='<b>&lt;</b>','<b>&gt;</b>'
32    strAttrib=''
33    for att in elem.attrib:
34        strAttrib+=' %s="%s"'%(span(att,'xmlAttrTyp'),span(elem.attrib[att],'xmlAttrVal'))
35    result='%s%s%s%s%s'%(lt,span(elem.tag,"xmlElemTag"),strAttrib,gt,match(elem.text))
36    children=len(elem)
37    if children:
38        for item in elem:
39            result+=PrettyPrintHTML(item)
40        result+='%s%s/%s%s'%(match(item.tail),lt,span(elem.tag,'xmlElemTag'),gt)
41    else:
42        result+='%s/%s%s'%(lt,span(elem.tag,'xmlElemTag'),gt)
43    return div(result,'xmlElem')
44
45
46
47
48
49def main():
50    sys.stderr = sys.stdout
51    print "Content-type: text/html"
52    print 
53    print "<HEAD>"
54    print '<STYLE TYPE="text/css">' 
55    print 'DIV.xmlElem {PADDING-LEFT: 20px;}'
56    #print '.highlight {BACKGROUND-COLOR:Yellow; }'
57    print '.xmlAttrVal {COLOR:Red; }'
58    print '.xmlAttrTyp {COLOR:Green; }'
59    print '.xmlElemTag {COLOR:Blue; }'
60    print "</STYLE>"
61    print "<title>CSML Test Parser</title>"
62    print "<h1>CSML Test Parser</h1>"
63    print "<p>Please note this is experimental, any questions please contact d.lowe@rl.ac.uk</p>"
64    print "<p>Parser version - 19 May 2006</p>"
65    print "<h2>Load a CSML file to test:</h2>"
66   
67    form = cgi.FieldStorage()
68    if not form:
69        print """<form action="http://glue.badc.rl.ac.uk/cgi-bin/csml/parseTest.py" method="POST" enctype="multipart/form-data">
70        <input type="file" name="filename">
71        <input type="submit">
72        </form>"""
73    elif form.has_key("filename"):
74        item = form["filename"]
75        if item.file:
76            data = item.file.read()
77            #print cgi.escape(data)
78            #data1 = cgi.escape(data)
79            f = open("/tmp/tempcsml.xml","wb")
80            f.write(data)
81            f.close()
82           
83            #NOW TRY AND PARSE THE FILE
84            #this is a fix to the  ElementTree namespace problem that namespaces are usually represented as ns0, ns1, ns2 etc.
85            etree._namespace_map.update({
86                    'http://www.opengis.net/om': 'om',  'http://www.opengis.net/gml': 'gml','http://ndg.nerc.ac.uk/csml' : 'csml', 'http://www.w3.org/1999/xlink':'xlink'})
87           
88           
89            #######################################################
90            # ElementTree-based parser test ROUND TRIP
91            #######################################################
92            # 1. Test parsing from CSML file
93            try:
94                tree = ElementTree(file='/tmp/tempcsml.xml')
95            except:
96                traceback.print_exc()
97                print "<p>Could not parse CSML</p>"
98                sys.exit()
99            dataset = Dataset()
100           
101            #Calling the fromXML method reads the CSML into memory.
102            try:
103                dataset.fromXML(tree.getroot())
104            except:
105                traceback.print_exc()
106                print "<p>Could not parse CSML</p>"
107                sys.exit()
108           
109
110           
111            #This creates a new CSML document string from the CSML objects in memory.
112
113            try:
114                csml = dataset.toXML()
115            except:
116                traceback.print_exc()
117                print "<p>Could not parse CSML</p>"
118                sys.exit()
119           
120
121            strCSML= PrettyPrintHTML(csml)
122            strCSML=parser_extra.removeInlineNS(strCSML)
123            print strCSML
124           
125            print "</HEAD>"
126main()
127
Note: See TracBrowser for help on using the repository browser.