def add_styles(self): """Add the css to the svg""" colors = self.graph.config.style.get_colors(self.id) all_css = [] for css in ['base.css'] + list(self.graph.css): if '://' in css: self.processing_instructions.append( etree.PI( u('xml-stylesheet'), u('href="%s"' % css))) else: if css.startswith('inline:'): css_text = css[len('inline:'):] else: if not os.path.exists(css): css = os.path.join( os.path.dirname(__file__), 'css', css) with io.open(css, encoding='utf-8') as f: css_text = template( f.read(), style=self.graph.config.style, colors=colors, font_sizes=self.graph.config.font_sizes(), id=self.id) if not self.graph.pretty_print: css_text = minify_css(css_text) all_css.append(css_text) self.node( self.defs, 'style', type='text/css').text = '\n'.join(all_css)
def __totree(self): ste_root = ET.Element('stexml') ste_root.text = '\n' ste_root.append(copy.deepcopy(self.__root__)) ste_root.addprevious(ET.PI('xml-stylesheet', 'type="text/xsl" href="stexml.xsl"')) tree = ET.ElementTree(ste_root) return tree
def __init__(self, graph): self.graph = graph if not graph.no_prefix: self.id = '#chart-%s ' % graph.uuid else: self.id = '' self.processing_instructions = [ etree.PI(u('xml'), u("version='1.0' encoding='utf-8'"))] self.root = etree.Element( "{%s}svg" % self.ns, nsmap={ None: self.ns, 'xlink': 'http://www.w3.org/1999/xlink', }) self.root.attrib['id'] = self.id.lstrip('#').rstrip() self.root.attrib['class'] = 'pygal-chart' self.root.append( etree.Comment(u( 'Generated with pygal %s ©Kozea 2011-2014 on %s' % ( __version__, date.today().isoformat())))) self.root.append(etree.Comment(u('http://pygal.org'))) self.root.append(etree.Comment(u('http://github.com/Kozea/pygal'))) self.defs = self.node(tag='defs') self.title = self.node(tag='title') self.title.text = graph.title or 'Pygal'
def render(self, path): if not self.last_render is None: # Comprobar si el icono del directorio ha cambiado. Si es así, forzar upd. if self.last_render.find('icon').text != self.icon: self.update_required = True if self.parent: self.parent.update_required = True self.parent.render(os.path.dirname(path)) if not self.last_render is None and not self.update_required: if (int(float(self.last_render.find('mtime').text)) == int( self.mtime) and int(float(self.last_render.find('size').text)) == int( self.size)): return if not self.last_render is None: # Comprobar si hay directorios que ya no deben existir en el proyecto for dir in os.walk(path).next()[1]: if dir in self._dirs_names: continue shutil.rmtree(os.path.join(path, dir)) level = '../' * self.relative_level root = self.build_xml(path=path) stylesheet = "../../%stemplates/dir.xsl" % ('../' * self.relative_level) pi = etree.PI('xml-stylesheet type="text/xsl" href="%s"' % stylesheet) root.addprevious(pi) tree = etree.ElementTree(root) tree.write(os.path.join(path, 'index.xml'), pretty_print=True, encoding='UTF-8', xml_declaration='1.0') render.write_render(root, os.path.join(path, 'index.html'))
def add_pi(self, name, **attrib): """Add a ProcessingInstruction""" text = self.attrib_text_re.search( etree.tostring(self.make_element('Fake', **attrib), encoding=unicode)) if text is not None: text = text.group(2) self.root.addprevious(etree.PI(name, text))
def tostring(self, encoding='unicode', **k): # override needed due to "getroottree" inclusion if self.root.getprevious() is None: self.root.addprevious( etree.PI('xml-stylesheet', 'type="text/xsl" href="/sheet.xsl"')) return etree.tostring(self.root.getroottree(), encoding=encoding, **k)
def getAtomStyleNodes(): ''' Returns stylesheet processing instruction nodes to include at the beginning of Atom feeds. ''' output = [etree.Comment('500B block to defeat firefox formatting. %s' % ('. ' * 500))] output.append(etree.PI('xml-stylesheet', 'type="text/xml" href="/static/atom.xsl"')) return output
def processing_instruction(target, text=None): """Create a processing instruction element In: - ``target`` -- the PI target - ``text`` -- the PI text Return: - the new processing instruction element """ return etree.PI(target, text)
def dump_subzdc(self, filename, subzdc): root_new = etree.Element("ZDC") root_new.addprevious( etree.PI('xml-stylesheet', 'href="ZDC0205.xsl" type="text/xsl"')) e_vorschrift = etree.SubElement(root_new, "VORSCHRIFT") e_direkt = etree.SubElement(e_vorschrift, "DIREKT") e_direkt.append(subzdc) # make a new tree from the new root tree_new = root_new.getroottree() tail_new = filename + '.' + subzdc.tag + '.xml' tree_new.write( tail_new, encoding="ISO-8859-1", doctype='<!DOCTYPE ZDC PUBLIC "ZDC0205.dtd" "ZDC0205.dtd">')
def to_xml(self, filename): fmi_root = etree.Element(self.xmlTagName) if self.fmiVersion == "2.0": addAttribute(fmi_root, 'fmiVersion', self.fmiVersion, required=True) addAttribute(fmi_root, 'modelName', self.modelName, required=True) addAttribute(fmi_root, 'guid', self.guid, required=True) addAttribute(fmi_root, 'description', self.description) addAttribute(fmi_root, 'author', self.author) addAttribute(fmi_root, 'version', self.version) addAttribute(fmi_root, 'copyright', self.copyright) addAttribute(fmi_root, 'license', self.license) addAttribute(fmi_root, 'generationTool', self.generationTool) addAttribute(fmi_root, 'generationDateAndTime', self.generationDateAndTime) addAttribute(fmi_root, 'variableNamingConvention', self.variableNamingConvention) addAttribute(fmi_root, 'numberOfEventIndicators', self.numberOfEventIndicators) addObject(fmi_root, self.CoSimulation, required=True) addObjects(fmi_root, 'UnitDefinitions', self.UnitDefinitions) addObjects(fmi_root, 'TypeDefinitions', self.TypeDefinitions) addObjects(fmi_root, 'LogCategories', self.LogCategories) addObject(fmi_root, self.DefaultExperiment) addObjects(fmi_root, 'VendorAnnotations', self.VendorAnnotations) addObjects(fmi_root, 'ModelVariables', self.ModelVariables, required=True) addObject(fmi_root, self.ModelStructure, required=True) else: raise RuntimeError('Unsupported FMI version: %s' % self.fmiVersion) if self.xml_stylesheet: fmi_root.addprevious( etree.PI('xml-stylesheet', 'type="text/xsl" href="%s"' % self.xml_stylesheet)) etree.ElementTree(fmi_root).write(filename, encoding="utf-8", pretty_print=True, xml_declaration=True)
def unscan(events, nsmap=None): """Converts events stream into lXML tree""" root = None last_closed_elt = None stack = [] for obj in events: if obj['type'] == ENTER: elt = _obj2elt(obj, nsmap=nsmap) if stack: stack[-1].append(elt) elif root is not None: raise RuntimeError('Event stream tried to create second XML tree') else: root = elt stack.append(elt) last_closed_elt = None elif obj['type'] == EXIT: last_closed_elt = stack.pop() elif obj['type'] == COMMENT: elt = et.Comment(obj['text']) stack[-1].append(elt) last_closed_elt = elt elif obj['type'] == PI: elt = et.PI(obj['target']) if obj.get('text'): elt.text = obj['text'] stack[-1].append(elt) last_closed_elt = elt elif obj['type'] == TEXT: text = obj['text'] if text: if last_closed_elt is None: stack[-1].text = (stack[-1].text or '') + text else: last_closed_elt.tail = (last_closed_elt.tail or '') + text else: assert False, obj if root is None: raise RuntimeError('Empty XML event stream') return root
def build(self, registry): self.root = etree.Element("node", {"version": "0.1"}) if self.xslt_url: pi = etree.PI('xml-stylesheet', 'type="text/xsl" href="%s"' % self.xslt_url) self.root.addprevious(pi) if issubclass(type(registry), Registry): self.build_features(registry.features) self.build_methods(registry.methods) elif isinstance(registry, Method.Result): self.build_result(registry) else: raise RuntimeError("Can not build XML for object: %s" % registry) return etree.tostring(self.root.getroottree(), pretty_print=True, xml_declaration=True, encoding='utf-8')
def __init__(self, graph): self.graph = graph self.processing_instructions = [ etree.PI(u'xml', u"version='1.0' encoding='utf-8'") ] self.root = etree.Element("{%s}svg" % self.ns, nsmap={ None: self.ns, 'xlink': 'http://www.w3.org/1999/xlink', }) self.root.append( etree.Comment(u'Generated with pygal %s ©Kozea 2012 on %s' % (__version__, date.today().isoformat()))) self.root.append(etree.Comment(u'http://pygal.org')) self.root.append(etree.Comment(u'http://github.com/Kozea/pygal')) self.defs = self.node(tag='defs')
def add_styles(self): """Add the css to the svg""" for css in ['base.css'] + list(self.graph.css): if urlparse(css).scheme: self.processing_instructions.append( etree.PI(u'xml-stylesheet', u'href="%s"' % css)) else: if not os.path.exists(css): css = os.path.join(os.path.dirname(__file__), 'css', css) with io.open(css, encoding='utf-8') as f: css_text = template(f.read(), style=self.graph.style, font_sizes=self.graph.font_sizes()) if not self.graph.pretty_print: css_text = minify_css(css_text) self.node(self.defs, 'style', type='text/css').text = css_text
def generate_xml_report(pathname): tmp = pathname.split('/')[-1] dirname = pathname.replace('/' + tmp, '') comm.mk_dir(dirname) print 'Save result into:' + pathname date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') root = et.Element('apks') root.addprevious( et.PI('xml-stylesheet', 'type="text/xsl" href="apk-analyser-result.xsl"')) root.attrib['datetime'] = date file = et.ElementTree(root) file.write(pathname, pretty_print=True, xml_declaration=True, encoding='utf-8')
def fucks_given_response(number_of_fucks, response_mime_type='application/json'): if response_mime_type == 'application/json': retval = response.json( { 'status': 'ok', 'f***s': ['f**k'] * number_of_fucks }, headers={'Cache-Control': 'no-cache'}, status=200) elif response_mime_type == 'application/xml': nsmap = {None: 'http://faas.unnecessary.tech/schema'} root = etree.Element( '{http://faas.unnecessary.tech/schema}ListOfFucks', nsmap=nsmap) status = etree.SubElement( root, '{http://faas.unnecessary.tech/schema}status') status.text = 'ok' f***s = etree.SubElement(root, '{http://faas.unnecessary.tech/schema}f***s') for i in range(number_of_fucks): a_fuck = etree.SubElement( f***s, '{http://faas.unnecessary.tech/schema}item') a_fuck.text = 'f**k' observation = etree.SubElement( root, '{http://faas.unnecessary.tech/schema}observation') observation.text = 'Why the f**k are you still using XML?' root.addprevious( etree.PI('xml-stylesheet', 'type="text/xsl" href="{}"'.format(xslt_url))) retval = response.raw(etree.tostring(root.getroottree(), encoding='UTF-8', xml_declaration=True), headers={ 'Content-Type': 'application/xml', 'Cache-Control': 'no-cache' }, status=200) else: retval = error_response( 'What f*****g mime type do you want for your reponse?') return retval
def error_response(error_message, status_code=500, response_mime_type='application/json'): if response_mime_type == 'application/json': retval = response.json({ 'status': 'error', 'message': error_message }, headers={'Cache-Control': 'no-cache'}, status=status_code) elif response_mime_type == 'application/xml': nsmap = {None: 'http://faas.unnecessary.tech/schema'} root = etree.Element('{http://faas.unnecessary.tech/schema}Error', nsmap=nsmap) status = etree.SubElement( root, '{http://faas.unnecessary.tech/schema}status') status.text = 'error' message = etree.SubElement( root, '{http://faas.unnecessary.tech/schema}message') message.text = error_message observation = etree.SubElement( root, '{http://faas.unnecessary.tech/schema}observation') observation.text = 'Why the f**k are you still using XML?' root.addprevious( etree.PI('xml-stylesheet', 'type="text/xsl" href="{}"'.format(xslt_url))) retval = response.raw(etree.tostring(root.getroottree(), encoding='UTF-8', xml_declaration=True), headers={ 'Content-Type': 'application/xml', 'Cache-Control': 'no-cache' }, status=status_code) else: retval = error_response( 'What f*****g mime type do you want for your reponse?') return retval
def render(self, path, stylesheet, name='index'): root = self.build_xml(path=path) if stylesheet != False: if path.endswith(os.sep): path = path[:-1] if not path: stylesheet_path = 'templates/' + stylesheet else: stylesheet_path = os.path.join('../' * len(path.split(os.sep)), 'templates/', stylesheet) pi = etree.PI('xml-stylesheet type="text/xsl" href="%s"' % stylesheet_path) root.addprevious(pi) tree = etree.ElementTree(root) tree.write(os.path.join(path, name + '.xml'), pretty_print=True, encoding='UTF-8', xml_declaration='1.0') if stylesheet != False: render.write_render(root, os.path.join(path, name + '.html'), stylesheet)
def tostring(self, encoding='unicode', **k): # override needed due to "getroottree" inclusion # and to add stylesheet stylesheets = [ x for x in self.root_siblings() if isinstance(x, etree.PIBase) and x.target == 'xml-stylesheet' ] for stylesheet in stylesheets: # remove all stylesheets present (be that ours or others') self.root.append( stylesheet ) # needed as we can't delete root siblings https://stackoverflow.com/a/60232366 self.root.remove(stylesheet) self.root.addprevious( etree.PI('xml-stylesheet', 'type="text/xsl" href="/sheet.xsl"')) return etree.tostring(self.root.getroottree(), encoding=encoding, method='xml', **k)
def parse_entity_gc(dblp_path, save_path, type_name, features=None, save_to_xml=False, include_key=False): """Parse specific elements according to the given type name and features""" log_msg("PROCESS: Start parsing for {}...".format(str(type_name))) assert features is not None, "features must be assigned before parsing the dblp dataset" results = [] i = 0 attrib_count, full_entity, part_entity = {}, 0, 0 root = etree.Element('dblp') root.addprevious(etree.PI('DOCTYPE', 'dblp SYSTEM "dblp.dtd"')) try: for _, elem in context_iter(dblp_path): if elem.tag in type_name: root.append(elem) i += 1 if i >= 100: break elif elem.tag not in all_elements: continue #clear_element(elem) except StopIteration: print("Fin du fichier") if save_to_xml: tree = etree.ElementTree(root) tree.write(save_path, pretty_print=True, xml_declaration=True, encoding="ISO-8859-1") else: # default save to json file with codecs.open(save_path, mode='w', encoding='utf8', errors='ignore') as f: ujson.dump(results, f) return full_entity, part_entity, attrib_count
def createFinvoice(expense, expenselines): top = Element('Finvoice') top.set('Version', '1.2') top.addprevious( etree.PI('xml-stylesheet', 'type="text/xsl" href="Finvoice.xsl"')) sp = SubElement(top, 'SellerPartyDetails') spi = SubElement(sp, 'SellerPartyIdentifier') spi.text = expense.personno.upper() spn = SubElement(sp, 'SellerOrganisationName') spn.text = expense.name spad = SubElement(sp, 'SellerPostalAddressDetails') ssn = SubElement(spad, 'SellerStreetName') ssn.text = expense.address scd = SubElement(top, 'SellerCommunicationDetails') sei = SubElement(scd, 'SellerEmailaddressIdentifier') sei.text = expense.email spni = SubElement(scd, 'SellerPhoneNumberIdentifier') spni.text = expense.phone si = SubElement(top, 'SellerInformationDetails') sa = SubElement(si, 'SellerAccountDetails') said = SubElement(sa, 'SellerAccountID') said.set('IdentificationSchemeName', 'IBAN') said.text = expense.iban sab = SubElement(sa, 'SellerBic') sab.set('IdentificationSchemeName', 'BIC') sab.text = expense.swift_bic b = SubElement(top, 'BuyerPartyDetails') bpi = SubElement(b, 'BuyerPartyIdentifier') bpi.text = expense.organisation.business_id bon = SubElement(b, 'BuyerOrganisationName') bon.text = expense.organisation.name i = SubElement(top, 'InvoiceDetails') itc = SubElement(i, 'InvoiceTypeCode') itc.text = 'INV01' itt = SubElement(i, 'InvoiceTypeText') itt.text = 'LASKU' i_n = SubElement(i, 'OriginCode') i_n.text = 'Original' i_n = SubElement(i, 'InvoiceNumber') i_n.text = str(expense.id) i_d = SubElement(i, 'InvoiceDate') i_d.set('Format', 'CCYYMMDD') i_d.text = expense.created_at.strftime('%Y%m%d') if expense.needsKatre(): i_ref = SubElement(i, 'BuyerReferenceIdentifier') i_ref.text = 'KATRE_EMCE' itvea = SubElement(i, 'InvoiceTotalVatExcludedAmount') itvea.set('AmountCurrencyIdentifier', 'EUR') itvea.text = currency(expense.amount(), '') itvva = SubElement(i, 'InvoiceTotalVatAmount') itvva.set('AmountCurrencyIdentifier', 'EUR') itvva.text = '0' itvia = SubElement(i, 'InvoiceTotalVatIncludedAmount') itvia.set('AmountCurrencyIdentifier', 'EUR') itvia.text = currency(expense.amount(), '') iv = SubElement(i, 'VatSpecificationDetails') ivba = SubElement(iv, 'VatBaseAmount') ivba.set('AmountCurrencyIdentifier', 'EUR') ivba.text = currency(expense.amount(), '') ivrp = SubElement(iv, 'VatRatePercent') ivrp.text = '0' ivra = SubElement(iv, 'VatRateAmount') ivra.set('AmountCurrencyIdentifier', 'EUR') ivra.text = '0' iftd = SubElement(i, 'InvoiceFreeText') iftd.text = expense.description iftm = SubElement(i, 'InvoiceFreeText') iftm.text = expense.memo for line in expenselines: row = SubElement(top, 'InvoiceRow') ran = SubElement(row, 'ArticleName') ran.text = line.expensetype.name + ': ' + line.description raq = SubElement(row, 'DeliveredQuantity') raq.set('QuantityUnitCode', line.expensetype.unit) raq.text = currency(line.basis, '') raa = SubElement(row, 'UnitPriceAmount') raa.set('AmountCurrencyIdentifier', 'EUR') raa.text = currency(line.expensetype.multiplier, '') ra = SubElement(row, 'RowShortProposedAccountIdentifier') ra.text = line.expensetype.account rd = SubElement(row, 'RowAccountDimensionText') if line.accountdimension: rd.text = line.accountdimension.code rvva = SubElement(row, 'RowVatRatePercent') rvva.text = '0' rvva = SubElement(row, 'RowVatAmount') rvva.set('AmountCurrencyIdentifier', 'EUR') rvva.text = '0' rvea = SubElement(row, 'RowVatExcludedAmount') rvea.set('AmountCurrencyIdentifier', 'EUR') rvea.text = currency(line.sum(), '') rva = SubElement(row, 'RowAmount') rva.set('AmountCurrencyIdentifier', 'EUR') rva.text = currency(line.sum(), '') # Nyt jännittää -Joonas # 10.1.2013 - Added if-statements to verify that the values actually exist if line.begin_at: rsd = SubElement(row, 'StartDate') rsd.set('Format', 'CCYYMMDD') rsd.text = line.begin_at.strftime('%Y%m%d') if line.ended_at: red = SubElement(row, 'EndDate') red.set('Format', 'CCYYMMDD') red.text = line.ended_at.strftime('%Y%m%d') if line.expensetype.requires_endtime: rft = SubElement(i, 'InvoiceFreeText') rft.text = ( line.expensetype.name + ', ' + line.description + ': ' + timezone.localtime(line.begin_at).strftime('%d.%m.%Y %H:%M') + ' - ' + timezone.localtime(line.ended_at).strftime('%d.%m.%Y %H:%M')) e = SubElement(top, 'EpiDetails') ei = SubElement(e, 'EpiIdentificationDetails') eid = SubElement(ei, 'EpiDate') eid.set('Format', 'CCYYMMDD') eid.text = expense.created_at.strftime('%Y%m%d') SubElement(ei, 'EpiReference') ep = SubElement(e, 'EpiPartyDetails') epb = SubElement(ep, 'EpiBfiPartyDetails') epbi = SubElement(epb, 'EpiBfiIdentifier') epbi.set('IdentificationSchemeName', 'BIC') epbi.text = expense.swift_bic epd = SubElement(ep, 'EpiBeneficiaryPartyDetails') epdn = SubElement(epd, 'EpiNameAddressDetails') epdn.text = expense.name epda = SubElement(epd, 'EpiAccountID') epda.set('IdentificationSchemeName', 'IBAN') epda.text = expense.iban ey = SubElement(e, 'EpiPaymentInstructionDetails') er = SubElement(ey, 'EpiRemittanceInfoIdentifier') er.set('IdentificationSchemeName', 'SPY') refno = str(expense.created_at.strftime('%Y')) + str(expense.id).zfill(5) from expenseapp.helpers import viitenumeron_tarkiste er.text = refno + str(viitenumeron_tarkiste(refno)) eya = SubElement(ey, 'EpiInstructedAmount') eya.set('AmountCurrencyIdentifier', 'EUR') eya.text = currency(expense.amount(), '') ec = SubElement(ey, 'EpiCharge') ec.set('ChargeOption', 'SHA') eyd = SubElement(ey, 'EpiDateOptionDate') eyd.set('Format', 'CCYYMMDD') eyd.text = expense.created_at.strftime('%Y%m%d') return tostring(top.getroottree(), encoding='UTF-8', xml_declaration=True, pretty_print=True)
def write_svg( svg: Union[str, IO[bytes]], xml: etree.Element, stylesheet: Optional[str] = None, do_link_css: bool = False, **tostring_kwargs, ) -> str: """ Write an xml element as an svg file. :param svg: open binary file object or path to output file (include extension .svg) :param xml: root node of your svg geometry :param stylesheet: optional path to css stylesheet :param do_link_css: link to stylesheet, else (default) write contents of stylesheet into svg (ignored if stylesheet is None) :param tostring_kwargs: keyword arguments to etree.tostring. xml_header=True for sensible default values. See below. :return: svg filename :effects: creates svg file at ``svg`` It's often useful to write a temporary svg file, so a tempfile.NamedTemporaryFile object (or any open binary file object can be passed instead of an svg filename). You may never need an xml_header. Inkscape doesn't need it, your browser doesn't need it, and it's forbidden if you'd like to "inline" your svg in an html file. The most pressing need might be to set an encoding. If you pass ``xml_declaration=True`` as a tostring_kwarg, this function will attempt to pass the following defaults to ``lxml.etree.tostring``: * doctype: str = ( '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"\n' '"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">' ) * encoding = "UTF-8" Always, this function will default to ``pretty_print=True`` These can be overridden by tostring_kwargs. e.g., ``write_svg(..., xml_declaration=True, doctype=None``) e.g., ``write_svg(..., xml_declaration=True, encoding='ascii')`` ``lxml.etree.tostring`` is documented here: https://lxml.de/api/index.html, but I know that to be incomplete as of 2020 Feb 01, as it does not document the (perhaps important to you) 'encoding' kwarg. """ if stylesheet is not None: if do_link_css is True: relative_css_path = Path(stylesheet).relative_to(Path(svg).parent) link = etree.PI("xml-stylesheet", f'href="{relative_css_path}" type="text/css"') xml.addprevious(link) else: style = etree.Element("style", type="text/css") with open(stylesheet) as css_file: style.text = etree.CDATA("\n" + "".join(css_file.readlines()) + "\n") xml.insert(0, style) svg_contents = svg_tostring(xml, **tostring_kwargs) try: svg.write(svg_contents) return svg.name except AttributeError: with open(svg, "wb") as svg_file: svg_file.write(svg_contents) return svg
def meta_data(self): """Output meta data to stdout including doctype""" xml_data = self.meta_data_xml() xml_data.addprevious(etree.PI('xm')) print (etree.tostring(xml_data, pretty_print=True, xml_declaration=True, encoding='utf-8', doctype="""<!DOCTYPE resource-agent SYSTEM "ra-api-1.dtd">""")) sys.stdout.write("\n")
os.path.abspath(arguments.stylesheet[0])) parsed_root.attrib['filename'] = os.path.abspath( arguments.input_filename[0]) parsed_tree = ET.ElementTree(parsed_root) if (arguments.transform): print(arguments.stylesheet[0]) xsl_file = open(arguments.stylesheet[0], 'r') xslt = ET.XSLT(ET.parse(xsl_file)) xsl_file.close() output = xslt(parsed_tree) elif (arguments.stylesheet): parsed_root.addprevious( ET.PI('xml-stylesheet', 'type="text/xsl" href="' + arguments.stylesheet[0] + '"')) output = parsed_tree if not (arguments.output_filename): print ET.tostring(output, pretty_print=True) else: output_file = open(arguments.output_filename[0], 'w') if not (arguments.transform): output.write(output_file, pretty_print=True, xml_declaration=True) else: output.write(output_file, pretty_print=True) output_file.close() out("Written to '" + arguments.output_filename[0] + "'") else:
def validate_hook(ret): global_msgs, single_elem, pkg_name = [], False, package_name() pi_comment = pkg_name + '-comment' # figure out the target element, skip if not any suitable if ret: # "protected" comments have to be turned to something # else, here a processing instruction cl = ret.xpath("//clufter:comment", namespaces={'clufter': CLUFTER_NS}) for e in cl: element_juggler.rebind( etree.PI(pi_comment, etree.tostring(e)), element_juggler.grab(e)) element_juggler.drop(e) #to_check = (ret.getroot(), ) root = ret.getroot() if root.tag == namespaced(CLUFTER_NS, "snippet"): to_check = reversed(root) else: to_check = (root, ) single_elem = True else: to_check = () worklist = list(i for i in to_check if xmltag_get_namespace(i.tag) != XSL_NS) use_offset = True while worklist: elem = worklist.pop() if elem is None: use_offset = True continue msgs, schema, schema_snippet = validator(elem, start=elem.tag) if not (msgs and schema and interactive): global_msgs.extend(msgs) break parent_pos = element_juggler.grab(elem) res_snippet = str_enc( etree.tostring(elem, pretty_print=True, encoding='UTF-8'), 'utf-8').strip() force = False for i in xrange(2, 0, -1): # 2 subsequent NOOPs -> termination try: elems, force = cls._try_edit(res_snippet.strip(), schema, schema_snippet, msgs, i, use_offset, **kws) except FilterError as e: log.warning(str(e)) elems = () if elems is not None: # active change break else: print( "Opportunity to recover the invalid (intermediate)" " result was repeatedly abandoned", file=stderr) elems = False if not elems: element_juggler.drop(elem) if elems is False: print("Terminating", file=stderr) raise SystemExit elif single_elem: assert len(elems) == 1 else: # positive change occurred (reverse due to insert) elems = reversed(elems) worklist.append(None) for e in elems: if not force: worklist.append(e) # ensure revalidation element_juggler.rebind(e, parent_pos) if force == 'block': return ret, () # validation for the whole block cancelled use_offset = False cl = ret.xpath( "//processing-instruction('{0}')".format(pi_comment)) for e in cl: # XXX could be done better? (e.text.strip().join((' ', ) * 2)) reverted = etree.fromstring(e.text, parser=etree_parser_safe) element_juggler.rebind( nselem( CLUFTER_NS, 'comment', *tuple(reverted if len(reverted) else args2tuple( reverted.text))), element_juggler.grab(e)) element_juggler.drop(e) return ret, global_msgs