Python elementtree.ElementTree.parse() Examples
The following are 15
code examples of elementtree.ElementTree.parse().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
elementtree.ElementTree
, or try the search function
.
Example #1
Source File: base.py From PySIGNFe with GNU Lesser General Public License v2.1 | 6 votes |
def _le_xml(self, arquivo): if arquivo is None: return False if not isinstance(arquivo, basestring): arquivo = etree.tounicode(arquivo) if arquivo is not None: if isinstance(arquivo, basestring): if NAMESPACE_NFSE in arquivo: arquivo = por_acentos(arquivo) if u'<' in arquivo: self._xml = etree.fromstring(tira_abertura(arquivo)) else: arq = open(arquivo) txt = ''.join(arq.readlines()) txt = tira_abertura(txt) arq.close() self._xml = etree.fromstring(txt) else: self._xml = etree.parse(arquivo) return True return False
Example #2
Source File: base.py From PySIGNFe with GNU Lesser General Public License v2.1 | 6 votes |
def validar(self): arquivo_esquema = self.caminho_esquema + self.arquivo_esquema # Aqui é importante remover a declaração do encoding # para evitar erros de conversão unicode para ascii xml = tira_abertura(self.xml).encode(u'utf-8') esquema = etree.XMLSchema(etree.parse(arquivo_esquema)) if not esquema.validate(etree.fromstring(xml)): for e in esquema.error_log: if e.level == 1: self.alertas.append(e.message.replace('{http://www.portalfiscal.inf.br/nfe}', '')) elif e.level == 2: self.erros.append(e.message.replace('{http://www.portalfiscal.inf.br/nfe}', '')) return esquema.error_log
Example #3
Source File: selftest.py From ru with GNU General Public License v2.0 | 6 votes |
def parsefile(): """ Test parsing from file. >>> tree = ElementTree.parse("samples/simple.xml") >>> normalize_crlf(tree) >>> tree.write(sys.stdout) <root> <element key="value">text</element> <element>text</element>tail <empty-element /> </root> >>> tree = ElementTree.parse("samples/simple-ns.xml") >>> normalize_crlf(tree) >>> tree.write(sys.stdout) <ns0:root xmlns:ns0="namespace"> <ns0:element key="value">text</ns0:element> <ns0:element>text</ns0:element>tail <ns0:empty-element /> </ns0:root> """
Example #4
Source File: packagepolicy.py From conary with Apache License 2.0 | 6 votes |
def _addCILPolicyProvides(self, path, pkgFiles, macros): if ElementTree is None: return try: keys = {'urn': '{urn:schemas-microsoft-com:asm.v1}'} fullpath = macros.destdir + path tree = ElementTree.parse(fullpath) root = tree.getroot() identity, redirect = root.find('runtime/%(urn)sassemblyBinding/%(urn)sdependentAssembly' % keys).getchildren() assembly = identity.get('name') self._addOneCILProvide(pkgFiles, path, assembly, redirect.get('oldVersion')) self.recipe.Requires(_CILPolicyProvides={ path: (assembly, redirect.get('newVersion'))}) except: return
Example #5
Source File: packagepolicy.py From conary with Apache License 2.0 | 6 votes |
def parseInfoFile(self, path): infoname = "info-%s:%s" % (os.path.basename(path), self.component) data = {} try: data = dict([x.strip().split('=', 1) \ for x in open(path).readlines()]) extraKeys = set(data.keys()).difference(self.legalKeys) if extraKeys: for key in extraKeys: self.error("%s is not is not a valid value for %s" % \ (key, infoname)) self.parseError = True except ValueError: self.error("Unable to parse info file for '%s'" % infoname) self.parseError = True return data
Example #6
Source File: solvers.py From MatchingMarkets.py with BSD 3-Clause "New" or "Revised" License | 5 votes |
def readsol(self,filename): """Read a CPLEX solution file""" try: import xml.etree.ElementTree as et except ImportError: import elementtree.ElementTree as et solutionXML = et.parse(filename).getroot() solutionheader = solutionXML.find("header") statusString = solutionheader.get("solutionStatusString") cplexStatus = { "optimal":LpStatusOptimal, } if statusString not in cplexStatus: raise PulpSolverError("Unknown status returned by CPLEX: "+statusString) status = cplexStatus[statusString] shadowPrices = {} slacks = {} shadowPrices = {} slacks = {} constraints = solutionXML.find("linearConstraints") for constraint in constraints: name = constraint.get("name") shadowPrice = constraint.get("dual") slack = constraint.get("slack") shadowPrices[name] = float(shadowPrice) slacks[name] = float(slack) values = {} reducedCosts = {} for variable in solutionXML.find("variables"): name = variable.get("name") value = variable.get("value") reducedCost = variable.get("reducedCost") values[name] = float(value) reducedCosts[name] = float(reducedCost) return status, values, reducedCosts, shadowPrices, slacks
Example #7
Source File: selftest.py From ru with GNU General Public License v2.0 | 5 votes |
def simpleparsefile(): """ Test the xmllib-based parser. >>> from elementtree import SimpleXMLTreeBuilder >>> parser = SimpleXMLTreeBuilder.TreeBuilder() >>> tree = ElementTree.parse("samples/simple.xml", parser) >>> normalize_crlf(tree) >>> tree.write(sys.stdout) <root> <element key="value">text</element> <element>text</element>tail <empty-element /> </root> """
Example #8
Source File: selftest.py From ru with GNU General Public License v2.0 | 5 votes |
def fancyparsefile(): """ Test the "fancy" parser. Sanity check. >>> from elementtree import XMLTreeBuilder >>> parser = XMLTreeBuilder.FancyTreeBuilder() >>> tree = ElementTree.parse("samples/simple.xml", parser) >>> normalize_crlf(tree) >>> tree.write(sys.stdout) <root> <element key="value">text</element> <element>text</element>tail <empty-element /> </root> Callback check. >>> class MyFancyParser(XMLTreeBuilder.FancyTreeBuilder): ... def start(self, elem): ... print "START", elem.tag ... def end(self, elem): ... print "END", elem.tag >>> parser = MyFancyParser() >>> tree = ElementTree.parse("samples/simple.xml", parser) START root START element END element START element END element START empty-element END empty-element END root """
Example #9
Source File: selftest.py From ru with GNU General Public License v2.0 | 5 votes |
def xinclude_loader(href, parse="xml", encoding=None): try: data = XINCLUDE[href] except KeyError: raise IOError("resource not found") if parse == "xml": return ElementTree.XML(data) return data
Example #10
Source File: device.py From jarvis with GNU General Public License v2.0 | 5 votes |
def parsexml_(*args, **kwargs): if (XMLParser_import_library == XMLParser_import_lxml and 'parser' not in kwargs): # Use the lxml ElementTree compatible parser so that, e.g., # we ignore comments. kwargs['parser'] = etree_.ETCompatXMLParser() doc = etree_.parse(*args, **kwargs) return doc # # User methods # # Calls to the methods in these classes are generated by generateDS.py. # You can replace these methods by re-implementing the following class # in a module named generatedssuper.py.
Example #11
Source File: device.py From jarvis with GNU General Public License v2.0 | 5 votes |
def parse(inFileName): doc = parsexml_(inFileName) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'root' rootClass = root rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None return rootObj
Example #12
Source File: device.py From jarvis with GNU General Public License v2.0 | 5 votes |
def main(): args = sys.argv[1:] if len(args) == 1: parse(args[0]) else: usage()
Example #13
Source File: service.py From jarvis with GNU General Public License v2.0 | 5 votes |
def parsexml_(*args, **kwargs): if (XMLParser_import_library == XMLParser_import_lxml and 'parser' not in kwargs): # Use the lxml ElementTree compatible parser so that, e.g., # we ignore comments. kwargs['parser'] = etree_.ETCompatXMLParser() doc = etree_.parse(*args, **kwargs) return doc # # User methods # # Calls to the methods in these classes are generated by generateDS.py. # You can replace these methods by re-implementing the following class # in a module named generatedssuper.py.
Example #14
Source File: service.py From jarvis with GNU General Public License v2.0 | 5 votes |
def parse(inFileName): doc = parsexml_(inFileName) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'scpd' rootClass = scpd rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None return rootObj
Example #15
Source File: cplex.py From GridCal with GNU General Public License v3.0 | 5 votes |
def readsol(self,filename): """Read a CPLEX solution file""" try: import xml.etree.ElementTree as et except ImportError: import elementtree.ElementTree as et solutionXML = et.parse(filename).getroot() solutionheader = solutionXML.find("header") statusString = solutionheader.get("solutionStatusString") cplexStatus = { "optimal":LpStatusOptimal, } if statusString not in cplexStatus: raise PulpSolverError("Unknown status returned by CPLEX: "+statusString) status = cplexStatus[statusString] shadowPrices = {} slacks = {} shadowPrices = {} slacks = {} constraints = solutionXML.find("linearConstraints") for constraint in constraints: name = constraint.get("name") shadowPrice = constraint.get("dual") slack = constraint.get("slack") shadowPrices[name] = float(shadowPrice) slacks[name] = float(slack) values = {} reducedCosts = {} for variable in solutionXML.find("variables"): name = variable.get("name") value = variable.get("value") reducedCost = variable.get("reducedCost") values[name] = float(value) reducedCosts[name] = float(reducedCost) return status, values, reducedCosts, shadowPrices, slacks