Last active
December 17, 2015 03:09
-
-
Save chadcooper/5541177 to your computer and use it in GitHub Desktop.
Credit to Mike Driscoll @ http://www.blog.pythonlibrary.org/2011/02/10/wxpython-showing-2-filetypes-in-wx-filedialog/ for the meat of the wxPython dialog and the XML parser is modified from http://code.activestate.com/recipes/573463-converting-xml-to-dictionary-and-back/.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import wx | |
import XmlToDict | |
class MyForm(wx.Frame): | |
def __init__(self): | |
wx.Frame.__init__(self, None, wx.ID_ANY, | |
"Multi-file type wx.FileDialog Tutorial") | |
panel = wx.Panel(self, wx.ID_ANY) | |
btn = wx.Button(panel, label="Open File Dialog") | |
btn.Bind(wx.EVT_BUTTON, self.onOpenFile) | |
self.g = XmlToDict.ConvertToFromXml() | |
def onOpenFile(self, event): | |
""" | |
Create and show the Open FileDialog | |
""" | |
dlg = wx.FileDialog( | |
self, message="Choose a file", | |
defaultFile="", | |
wildcard="XML files (*.xml)|*.xml", | |
style=wx.OPEN | wx.CHANGE_DIR) | |
if dlg.ShowModal() == wx.ID_OK: | |
f = dlg.GetPath() | |
self.parse_xml(f) | |
dlg.Destroy() | |
def parse_xml(self, in_file): | |
config = self.g.ConvertXmlToDict(str(in_file)) | |
root = config["VIESORE.Configuration"] | |
kops = root["KOP"] | |
if not isinstance(kops, list): | |
kops = [kops] | |
print kops | |
print len(kops) | |
if __name__ == "__main__": | |
app = wx.App(False) | |
frame = MyForm() | |
frame.Show() | |
app.MainLoop() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from xml.etree import ElementTree | |
class ConvertToFromXml(object): | |
class XmlDictObject(dict): | |
""" | |
Adds object like functionality to the standard dictionary. | |
""" | |
def __init__(self, initdict=None): | |
if initdict is None: | |
initdict = {} | |
dict.__init__(self, initdict) | |
def __getattr__(self, item): | |
return self.__getitem__(item) | |
def __setattr__(self, item, value): | |
self.__setitem__(item, value) | |
def __str__(self): | |
if self.has_key('_text'): | |
return self.__getitem__('_text') | |
else: | |
return '' | |
@staticmethod | |
def Wrap(self, x): | |
""" | |
Static method to wrap a dictionary recursively as an XmlDictObject | |
""" | |
if isinstance(x, dict): | |
return self.XmlDictObject((k, self.XmlDictObject.Wrap(v)) for (k, v) in x.iteritems()) | |
elif isinstance(x, list): | |
return [self.XmlDictObject.Wrap(v) for v in x] | |
else: | |
return x | |
@staticmethod | |
def _UnWrap(self, x): | |
if isinstance(x, dict): | |
return dict((k, self.XmlDictObject._UnWrap(v)) for (k, v) in x.iteritems()) | |
elif isinstance(x, list): | |
return [self.XmlDictObject._UnWrap(v) for v in x] | |
else: | |
return x | |
def UnWrap(self): | |
""" | |
Recursively converts an XmlDictObject to a standard dictionary and returns the result. | |
""" | |
return self.XmlDictObject._UnWrap(self) | |
def _ConvertDictToXmlRecurse(self, parent, dictitem): | |
assert type(dictitem) is not type([]) | |
if isinstance(dictitem, dict): | |
for (tag, child) in dictitem.iteritems(): | |
if str(tag) == '_text': | |
parent.text = str(child) | |
elif type(child) is type([]): | |
# iterate through the array and convert | |
for listchild in child: | |
elem = ElementTree.Element(tag) | |
parent.append(elem) | |
self._ConvertDictToXmlRecurse(elem, listchild) | |
else: | |
elem = ElementTree.Element(tag) | |
parent.append(elem) | |
self._ConvertDictToXmlRecurse(elem, child) | |
else: | |
parent.text = str(dictitem) | |
def ConvertDictToXml(self, xmldict): | |
""" | |
Converts a dictionary to an XML ElementTree Element | |
""" | |
roottag = xmldict.keys()[0] | |
root = ElementTree.Element(roottag) | |
self._ConvertDictToXmlRecurse(root, xmldict[roottag]) | |
return root | |
def _ConvertXmlToDictRecurse(self, node, dictclass): | |
nodedict = dictclass() | |
if len(node.items()) > 0: | |
# if we have attributes, set them | |
nodedict.update(dict(node.items())) | |
for child in node: | |
# recursively add the element's children | |
newitem = self._ConvertXmlToDictRecurse(child, dictclass) | |
if nodedict.has_key(child.tag): | |
# found duplicate tag, force a list | |
if type(nodedict[child.tag]) is type([]): | |
# append to existing list | |
nodedict[child.tag].append(newitem) | |
else: | |
# convert to list | |
nodedict[child.tag] = [nodedict[child.tag], newitem] | |
else: | |
# only one, directly set the dictionary | |
nodedict[child.tag] = newitem | |
if node.text is None: | |
text = '' | |
else: | |
text = node.text.strip() | |
if len(nodedict) > 0: | |
# if we have a dictionary add the text as a dictionary value (if there is any) | |
if len(text) > 0: | |
nodedict['_text'] = text | |
else: | |
# if we don't have child nodes or attributes, just set the text | |
nodedict = text | |
return nodedict | |
def ConvertXmlToDict(self, root, dictclass=XmlDictObject): | |
""" | |
Converts an XML file or ElementTree Element to a dictionary | |
""" | |
# If a string is passed in, try to open it as a file | |
if type(root) == type(''): | |
root = ElementTree.parse(root).getroot() | |
elif not isinstance(root, ElementTree.Element): | |
raise TypeError, 'Expected ElementTree.Element or file path string' | |
return dictclass({root.tag: self._ConvertXmlToDictRecurse(root, dictclass)}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment