]>
Commit | Line | Data |
---|---|---|
1 | """ | |
2 | Build a GUI Tree (wxWindows) from an XML file | |
3 | using pyExpat | |
4 | """ | |
5 | ||
6 | import sys,string | |
7 | from xml.parsers import pyexpat | |
8 | ||
9 | from wxPython.wx import * | |
10 | ||
11 | class MyFrame(wxFrame): | |
12 | def __init__(self, parent, id, title): | |
13 | wxFrame.__init__(self, parent, id, title, wxPoint(100, 100), wxSize(160,100)) | |
14 | menu = wxMenu() | |
15 | menu.Append (1001,"Open") | |
16 | menu.Append (1002,"Close") | |
17 | menu.Append (1003,"Exit") | |
18 | menubar = wxMenuBar() | |
19 | menubar.Append (menu,"File") | |
20 | self.SetMenuBar(menubar) | |
21 | ||
22 | class MyApp(wxApp): | |
23 | def OnInit(self): | |
24 | self.frame = MyFrame(NULL, -1, "Tree View of XML") | |
25 | self.tree = wx.wxTreeCtrl(self.frame, -1) | |
26 | EVT_MENU(self, 1001, self.OnOpen) | |
27 | EVT_MENU(self, 1002, self.OnClose) | |
28 | EVT_MENU(self, 1003, self.OnExit) | |
29 | self.frame.Show(true) | |
30 | self.SetTopWindow(self.frame) | |
31 | return true | |
32 | ||
33 | def OnOpen(self,event): | |
34 | f = wxFileDialog(self.frame,"Select a file",".","","*.xml",wxOPEN) | |
35 | if f.ShowModal() == wxID_OK: | |
36 | LoadTree(f.GetPath()) | |
37 | ||
38 | def OnClose(self,event): | |
39 | self.tree = wx.wxTreeCtrl(self.frame, -1) | |
40 | pass | |
41 | ||
42 | def OnExit(self,event): | |
43 | self.OnCloseWindow(event) | |
44 | ||
45 | def OnCloseWindow(self, event): | |
46 | self.frame.Destroy() | |
47 | ||
48 | ||
49 | NodeStack = [] | |
50 | ||
51 | # Define a handler for start element events | |
52 | def StartElement( name, attrs ): | |
53 | global NodeStack | |
54 | NodeStack.append(app.tree.AppendItem(NodeStack[-1],name)) | |
55 | ||
56 | def EndElement( name ): | |
57 | global NodeStack | |
58 | NodeStack = NodeStack[:-1] | |
59 | ||
60 | def CharacterData ( data ): | |
61 | global NodeStack | |
62 | if string.strip(data): | |
63 | app.tree.AppendItem(NodeStack[-1],data) | |
64 | ||
65 | ||
66 | def LoadTree (f): | |
67 | print f | |
68 | # Create a parser | |
69 | Parser = pyexpat.ParserCreate() | |
70 | ||
71 | # Tell the parser what the start element handler is | |
72 | Parser.StartElementHandler = StartElement | |
73 | Parser.EndElementHandler = EndElement | |
74 | Parser.CharacterDataHandler = CharacterData | |
75 | ||
76 | # Parse the XML File | |
77 | ParserStatus = Parser.Parse(open(f,'r').read(), 1) | |
78 | if ParserStatus == 0: | |
79 | print "oops!" | |
80 | raise SystemExit | |
81 | ||
82 | app = MyApp(0) | |
83 | NodeStack = [app.tree.AddRoot("Root")] | |
84 | ||
85 | ||
86 | app.MainLoop() | |
87 | raise SystemExit |