def Load(self, path="settings.dat"): #Get settings for the settings.xml file #Change the xml to dat. This will be removed in later versions. if File.Exists(common.SCRIPTDIRECTORY + "settings.xml"): File.Move(common.SCRIPTDIRECTORY + "settings.xml", common.SCRIPTDIRECTORY + path) if File.Exists(common.SCRIPTDIRECTORY + path): xreader = XmlReader.Create(common.SCRIPTDIRECTORY + path) while xreader.Read(): if xreader.Name == "DisplayCovers": self.DisplayCovers = xreader.ReadElementContentAsBoolean() #print self.DisplayCovers if xreader.Name == "DownloadCovers": self.DownloadCovers = xreader.ReadElementContentAsBoolean() #print self.DownloadCovers if xreader.Name == "BlackList": blacklist = xreader.ReadElementContentAsString() self.BlackList = blacklist.split(",") #print self.BlackList if xreader.Name == "DisplayPrice": self.DisplayPrice = xreader.ReadElementContentAsBoolean() if xreader.Name == "DisplayPublisher": self.DisplayPublisher = xreader.ReadElementContentAsBoolean() if xreader.Name == "Export": self.Export = xreader.ReadElementContentAsBoolean() xreader.Close() xreader.Dispose() else: print "settings.xml does not exist yet....\nUsing default values" return
def get_rss2(url): try: with XmlReader.Create(url) as reader: return [ RSSItem( i.Title.Text, i.Summary.Text, i.Links[0].Uri.AbsoluteUri if i.Links.Count > 0 else "") for i in SyndicationFeed.Load(reader).Items ] except XmlException: wc = WebClient() wc.Encoding = UTF8 xmlstr = wc.DownloadString(url) xdoc = XmlDocument() xdoc.LoadXml(xmlstr) xelem = xdoc.DocumentElement titles = [ i.InnerText.Replace("\n", "").Replace("\r", "") for i in xelem.SelectNodes("//item//title") ] links = [i.InnerText for i in xelem.SelectNodes("//item//link")] descriptions = [ i.InnerText for i in xelem.SelectNodes("//item//description") ] return [ RSSItem(t, d, l) for t, d, l in zip(titles, descriptions, links) ]
def deserialize(self, source, prefixes=None, strict=False, as_attribute=None, as_list=None, as_attribute_of_element=None): if isinstance(source, basestring): try: if os.path.exists(source): xtr = XmlTextReader(StreamReader(source)) except ValueError: xtr = XmlTextReader(StringReader(source)) else: xtr = XmlTextReader(StringReader(source)) elif hasattr(source, 'read'): xtr = XmlTextReader(StringReader(source.read())) settings = XmlReaderSettings() settings.ProhibitDtd = True reader = XmlReader.Create(xtr, settings) document = Document() document.as_attribute = as_attribute or {} document.as_list = as_list or {} document.as_attribute_of_element = as_attribute_of_element or {} self._deserialize(reader, document) xtr.Close() reader.Close() return document
def __deserialize_from_xml(file_full_name): iaddin_custom_frame_instance = None try: filereader = None try: filereader = File.OpenText(file_full_name) if filereader: content = filereader.ReadToEnd() stringreader = StringReader(content) xmlreader = None try: xmlreader = XmlReader.Create(stringreader) if xmlreader: iaddin_custom_frame_instance = XamlReader.Load( xmlreader) finally: if xmlreader: xmlreader.Dispose() xmlreader = None finally: if filereader: filereader.Dispose() filereader = None except Exception as e: CommonUtil.sprint("Failed to desrialize: {}".format(e)) iaddin_custom_frame_instance = None return iaddin_custom_frame_instance
def __init__(self, xaml): self._xaml = xaml xr = XmlReader.Create(StringReader(self._xaml)) self.winLoad = wpf.LoadComponent(self, xr) #self._comboBox = self.winLoad.FindName('_comboBox') # not necessary with wpf IronPython Module Wpf for x in range(1, 10): self._comboBox.Items.Add("Item " + str(x))
def __init__(self, overlay: OverlayWindow): self.overlay = overlay self.window = XamlReader.Load( XmlReader.Create(StringReader(SettingsXaml))) self.InitializeComponent() self.LoadConfig()
def _handle_empty_fragment(self, fragment): xtr = XmlTextReader(StringReader(str(fragment) + '/>')) reader = XmlReader.Create(xtr, self.settings) while reader.Read(): node_type = reader.NodeType if node_type == XmlNodeType.Element: return self.handle_start_element(reader)
def __init__(self, xaml): self._xaml = xaml xr = XmlReader.Create(StringReader(xaml)) self.winLoad = XamlReader.Load(xr) self._button = self.winLoad.FindName('button') self._stakpanel = self.winLoad.FindName('stackPanel') self._button.Click += self.onClick
def __init__(self, mode): f = FileStream(Path.Combine(SCRIPTDIRECTORY, "DuplicateForm.xaml"), FileMode.Open) self.win = XamlReader.Load(XmlReader.Create(f)) f.Close() self._action = None self.RenameText = "The file you are moving will be renamed: " #Load the images and icon path = FileInfo(__file__).DirectoryName arrow = BitmapImage() arrow.BeginInit() arrow.UriSource = Uri(Path.Combine(SCRIPTDIRECTORY, "arrow.png"), UriKind.Absolute) arrow.EndInit() self.win.FindName("Arrow1").Source = arrow self.win.FindName("Arrow2").Source = arrow self.win.FindName("Arrow3").Source = arrow icon = BitmapImage() icon.BeginInit() icon.UriSource = Uri(ICON, UriKind.Absolute) icon.EndInit() self.win.Icon = icon self.win.FindName("CancelButton").Click += self.CancelClick self.win.FindName("Cancel").Click += self.CancelClick self.win.FindName("ReplaceButton").Click += self.ReplaceClick self.win.FindName("RenameButton").Click += self.RenameClick self.win.Closing += self.FormClosing #The the correct text based on what mode we are in #Mode is set by default so only change if in Copy or Simulation mode if mode == Mode.Copy: self.win.FindName("MoveHeader").Content = "Copy and Replace" self.win.FindName( "MoveText" ).Content = "Replace the file in the destination folder with the file you are copying:" self.win.FindName("DontMoveHeader").Content = "Don't Copy" self.win.FindName( "RenameHeader").Content = "Copy, but keep both files" self.RenameText = "The file you are copying will be renamed: " self.win.FindName( "RenameText" ).Text = "The file you are copying will be renamed: " if mode == Mode.Simulate: self.win.FindName( "Subtitle" ).Content = "Click the file you want to keep (simulated, no files will be deleted or moved)"
def test_external_assemblies(self): import clr clr.AddReferenceByPartialName('System.Xml') from System.IO import StringReader from System.Xml import XmlReader buffer = StringReader("<foo>test</foo>") xml = XmlReader.Create(buffer) xml.ReadStartElement("foo") assert xml.ReadString() == 'test' xml.ReadEndElement()
def _parse(self, reader): settings = XmlReaderSettings(ProhibitDtd=False) reader = XmlReader.Create(reader, settings) self._reader = reader while reader.Read(): nodetype = reader.NodeType typename = Enum.GetName(XmlNodeType, nodetype) handler = getattr(self, '_handle_' + typename, None) if handler is not None: handler()
def __init__(self): self.window = XamlReader.Load( XmlReader.Create(StringReader(OverlayXaml))) self.console = Console() self.InitializeComponent() self.LoadConfig() self.settings = SettingsWindow(self) self.Run()
def parse(xml): # see issue 379, and https://stackoverflow.com/questions/215854/ settings = XmlReaderSettings() settings.XmlResolver = None settings.DtdProcessing = DtdProcessing.Ignore settings.ProhibitDtd = False with XmlReader.Create(xml, settings) as xr: while xr.Read(): xr.MoveToContent() node = XmlNode(xr) yield node if xr.IsEmptyElement: node.nodeType = XmlNodeType.EndElement del node.attributes yield node
def __read(self): try: filestream = File.OpenRead(self.file_location) xml = XmlReader.Create(filestream) if self.progress: self.progress.filestream = filestream except IOError as e: raise e else: if xml.IsStartElement('osm'): self.__readOsmEntities(xml) else: print('Osm file is not valid. No <osm> element found.\n') finally: if File.Exists(self.file_location): xml.Close() filestream.Close()
def close(self): """Parse the XML from the internal buffer to build an element tree. :return: the root element of the XML document :rtype: :class:`xml.etree.ElementTree.ElementTree` """ xml_string = "".join(self._buffer) self._buffer = None reader = XmlReader.Create(StringReader(xml_string), self.settings) # figure out which encoding to use next = reader.Read() document_encoding = ( reader.GetAttribute("encoding") if next and reader.NodeType == XmlNodeType.XmlDeclaration else None) if document_encoding: self.__log.info( "parsed document encoding %r from XML declaration", document_encoding) else: document_encoding = "UTF-8" self.__log.warn( "document encoding is missing! assuming default %r", document_encoding) while next: if reader.IsStartElement(): self._start_element(reader) elif reader.NodeType in [XmlNodeType.Text, XmlNodeType.CDATA]: # decode the value first to work around IronPython quirk self._target.data(reader.Value.decode(document_encoding)) elif reader.NodeType == XmlNodeType.EndElement: self._target.end(reader.LocalName) next = reader.Read() return self._target.close()
def close(self): """Parse the XML from the internal buffer to build an element tree. Returns ------- :class:`xml.etree.ElementTree.ElementTree` The root element of the XML document """ xml_string = "".join(self._buffer) self._buffer = None reader = XmlReader.Create(StringReader(xml_string), self.settings) while reader.Read(): if reader.IsStartElement(): self._start_element(reader) elif reader.NodeType in [XmlNodeType.Text, XmlNodeType.CDATA]: self._target.data(reader.Value.decode(self._document_encoding)) elif reader.NodeType == XmlNodeType.EndElement: self._target.end(reader.Name) elif reader.NodeType == XmlNodeType.XmlDeclaration: self._parse_xml_declaration(reader.Value) return self._target.close()
t4 = 'talk!' txt = controls['TextBox']['Text'] print 'B1' in str(s) if 'B1' in str(s): txt.Text += t1 elif 'B2' in str(s): txt.Text += t2 elif 'B3' in str(s): txt.Text += t3 elif 'B4' in str(s): txt.Text += t4 def talk(s, e): spk = SpeechSynthesizer() spk.Speak(controls['TextBox']['Text'].Text) file = FileStream(xaml_path, FileMode.Open, FileAccess.Read) xr = XmlReader.Create(file) win = XamlReader.Load(xr) controls = {} Waddle(win, controls) if __name__ == "__main__": for butt in controls['Button']: if butt != 'Speak': controls['Button'][butt].Click += changeSpeech controls['Button']['Speak'].Click += talk Application().Run(win)
def __init__(self): self.window = XamlReader.Load( XmlReader.Create(StringReader(ConsoleXaml))) self.InitializeComponent()
import os import time import datetime from PythonFileReader import PythonFileReader from CreateBackup import createBackup from System.Xml import XmlReader DB_HOST = '' DB_USER = '' DB_USER_PASSWORD = '' DB_NAMES = '' BACKUP_PATH = '' f = open('configuracion.xml') fr = PythonFileReader(f) xr = XmlReader.Create(fr) while xr.Read(): if xr.IsStartElement(): if xr.Name == 'host': DB_HOST = xr.GetAttribute("name") if xr.Name == 'user': DB_USER = xr.GetAttribute("name") if xr.Name == 'pass': DB_USER_PASSWORD = xr.GetAttribute("name") if xr.Name == 'path': BACKUP_PATH = xr.GetAttribute("name") if xr.Name == 'database': DB_NAMES += ',' + xr.GetAttribute("name") print DB_HOST, DB_USER, DB_USER_PASSWORD, DB_NAMES, BACKUP_PATH ARRAY_DB_NAME = DB_NAMES.split(',') for DB_NAME in ARRAY_DB_NAME: if DB_NAME:
import clr clr.AddReference("PresentationFramework") clr.AddReference("System.Xml") from System.Xml import XmlReader from System.Windows.Markup import XamlReader xaml = XmlReader.Create("app.xaml") app = XamlReader.Load(xaml) xaml.Close() app.Run()
def __init__(self, xaml): self._xaml = xaml xr = XmlReader.Create(StringReader(self._xaml)) self.winLoad = wpf.LoadComponent(self, xr)
def main(): try: opts, args = getopt.getopt(sys.argv[1:], "hvo:", ["help", "version", "output="]) except getopt.GetoptError as err: print str(err) sys.exit(2) output = None for o, a in opts: if o == "-v": usage() sys.exit(0) elif o in ("-h", "--help"): usage() sys.exit(0) elif o in ("-o", "--output"): output = a else: assert False, "unknown option" ret = 0 if output == None: print "no output option" ret += 1 if ret != 0: sys.exit(1) print "connect {0}".format(output) conn = sqlite3.connect(output) sql = "DROP TABLE IF EXISTS test_table;" conn.execute(sql) sql = "CREATE TABLE test_table ( id INTEGER PRIMARY KEY AUTOINCREMENT, key VARCHAR(256), val VARCHAR(256));" conn.execute(sql) conn.commit() insert_record(conn, 'hoge', 'foo') for input in args: print "read {0}".format(input) reader = XmlReader.Create(PythonFileReader(open(input))) while reader.Read(): nodetype = reader.NodeType if nodetype == XmlNodeType.Element: name = reader.Name if name == "record": #print "tag is " + reader.Name doc = XElement.Load(reader.ReadSubtree()) #print doc.ToString() # 複数の値を取り出すときは Descendantsを使う。 #for node in doc.Descendants("key"): # key = node.Value #for node in doc.Descendants("val"): # val = node.Value # 値を1つ取り出すときはElementを使う。 # convert ascii string to unicode key = doc.Element("key").Value val = doc.Element("val").Value print 'key is ' + key.decode('utf-8') print 'val is ' + val.decode('utf-8') insert_record(conn, key, val) elif nodetype == XmlNodeType.Text: #print reader.Value pass elif nodetype == XmlNodeType.EndElement: name = reader.Name if name == "record": #print "end of " + reader.Name pass reader.Close() conn.commit() dump_records_name(conn) conn.close()
def _ironparse(source): # internal event generator. takes a TextReader subclass, a file- # like object, or a filename, and generates an event stream. use # the parse() and iterparse() adapters to access this from user- # code. if isinstance(source, TextReader): pass # use as is elif hasattr(source, "read"): # FIXME: implement TextReader wrapper for Python I/O objects source = StringReader(source.read()) # FIXME: handle settings here? (disable comments, etc) reader = XmlReader.Create(source) # tag cache tags = {} namespaces = [] def gettag(): key = reader.NamespaceURI, reader.LocalName try: tag = tags[key] except KeyError: if key[0]: tag = "{%s}%s" % key else: tag = key[1] tags[key] = tag return tag while reader.Read(): node = reader.NodeType if node == START: tag = gettag() attrib = {} ns = 0 # count namespace declarations while reader.MoveToNextAttribute(): if reader.LocalName == "xmlns": ns += 1 # default namespace yield "start-ns", ("", reader.Value) elif reader.Prefix == "xmlns": ns += 1 # prefixed namespace yield "start-ns", (reader.LocalName, reader.Value) else: attrib[gettag()] = reader.Value namespaces.append(ns) reader.MoveToElement() yield "start", tag, attrib if reader.IsEmptyElement: yield "end", tag for i in xrange(namespaces.pop()): yield "end-ns", None elif node == END: yield "end", tags[reader.NamespaceURI, reader.LocalName] for i in xrange(namespaces.pop()): yield "end-ns", None elif node == DATA_TEXT or node == DATA_SPACE or node == DATA_CDATA: yield "data", reader.Value else: pass # yield "unknown", node reader.Close()
def _handle_fragment(self, fragment, depth): xtr = XmlTextReader(StringReader(str(fragment))) reader = XmlReader.Create(xtr, self.settings) sub_elements = iter(fragment.sub_elements) self._deserialize(reader, fragment, sub_elements, depth)
def InitializeComponent(self): self.server = "eu" self.window.MouseLeftButtonDown += self.MoveOverlay self.window.MouseLeftButtonUp += self.SaveOverlayPos self.window.MouseRightButtonUp += self.OverlayRightClick grid = LogicalTreeHelper.FindLogicalNode(self.window, "Grid") self.label = XamlReader.Load( XmlReader.Create(StringReader(OverlayLabelXaml))) self.check_label = XamlReader.Load( XmlReader.Create(StringReader(OverlayLabelXaml))) self.check_label.VerticalAlignment = 0 self.check_label.HorizontalAlignment = 0 self.check_label.Background = BrushFromHex("#00000000") self.check_label.Foreground = BrushFromHex("#00000000") self.check_label.Content = "9999ms" grid.Children.Add(self.label) grid.Children.Add(self.check_label) # Overlay menu self.menu = System.Windows.Forms.ContextMenuStrip() settings_item = System.Windows.Forms.ToolStripMenuItem("Settings") settings_item.Click += self.OpenSettings console_item = System.Windows.Forms.ToolStripMenuItem("Console") console_item.Click += self.OpenConsole respos_item = System.Windows.Forms.ToolStripMenuItem("Reset position") respos_item.Click += self.ResetPos close_item = System.Windows.Forms.ToolStripMenuItem("Close") close_item.Click += self.CloseOverlay self.menu.Items.Add(settings_item) self.menu.Items.Add(console_item) self.menu.Items.Add(respos_item) self.menu.Items.Add(close_item) # Icon menu menu_icon = System.Windows.Forms.ContextMenu() settings_item_icon = System.Windows.Forms.MenuItem("Settings") settings_item_icon.Click += self.OpenSettings console_item_icon = System.Windows.Forms.MenuItem("Console") console_item_icon.Click += self.OpenConsole respos_item_icon = System.Windows.Forms.MenuItem("Reset position") respos_item_icon.Click += self.ResetPos close_item_icon = System.Windows.Forms.MenuItem("Close") close_item_icon.Click += self.CloseOverlay menu_icon.MenuItems.Add(settings_item_icon) menu_icon.MenuItems.Add(console_item_icon) menu_icon.MenuItems.Add(respos_item_icon) menu_icon.MenuItems.Add(close_item_icon) notify_icon = System.Windows.Forms.NotifyIcon() notify_icon.Text = "Brawlhalla Display Ping" notify_icon.Icon = System.Drawing.Icon(ResourcePath("icon.ico")) notify_icon.ContextMenu = menu_icon notify_icon.Click += self.ClickTrayIcon notify_icon.Visible = True
if hasattr(c,"Children"): for cc in c.Children: Waddle(cc, d) elif hasattr(c,"Child"): Waddle(c.Child, d) elif hasattr(c,"Content"): Waddle(c.Content, d) # Test Functions. def sayhello(s,e): print "sayhello" def sayhello2(s,e): print "sayhello2" if __name__ == "__main__": xr = XmlReader.Create(StringReader(xaml)) win = XamlReader.Load(xr) controls = {} Waddle(win, controls) #Make all Named buttons do something! for butt in controls['Button']: controls['Button'][butt].Click += sayhello #Make one button do something. controls['Button']['NewSite'].Click += sayhello2 Application().Run(win) xr = XmlReader.Create(StringReader(xaml)) win = XamlReader.Load(xr)