[Python] How to pass dynamic or external variable's (path) text to the class

Discussão em 'Python' iniciado por Stack, Maio 27, 2025.

  1. Stack

    Stack Membro Participativo

    Below code taken from Rolfbly, with yours permission, I requested here for how to pass the dynamic path for the XSLT.

    from saxonche import PySaxonProcessor
    from pathlib import Path
    import argparse

    stylesheet_file1=r'D:\Test\Stream.xsl' # instead of static path, need to pass dynamic or global variable text,
    #how to pass here, see code-101 in commented text below
    #stylesheet_file1=fxsl # this path or variable text needs to assign

    class Xslt_proc():
    proc = PySaxonProcessor(license = False)
    nuproc = proc.new_xslt30_processor()
    xform = nuproc.compile_stylesheet(stylesheet_file=stylesheet_file1)

    def transform(processor, infile, sfx):
    outfname = r'D:\Test\Stream_out.xml'
    doc = processor.proc.parse_xml(xml_file_name=infile)
    out = processor.xform.transform_to_string(xdm_node=doc)

    with open(outfname, 'w') as f:
    f.write(out)

    def parse_arguments():
    parser = argparse.ArgumentParser(description="XML XSLT ResultName")
    parser.add_argument('param1', type=str, help="XML file")
    parser.add_argument('param2', type=str, help="XSL file")

    def main():
    try:
    args = parse_arguments()
    f_xml=args.param1
    f_xsl=args.param2
    except:
    # Define file names
    f_xml = r'D:\Test\Stream.xml'
    f_xsl = r'D:\Test\Stream.xsl' #code-101, this path needs to add in class 'Xslt_proc'

    P = Xslt_proc()
    transform(P, f_xml, '_done')

    if __name__ == "__main__":
    main()


    XSLT3

    <xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="@*|node()">
    <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
    </xsl:template>

    <xsl:template match="title">
    <xsl:element name="mainTitle">
    <xsl:apply-templates select="@*"/>
    <xsl:apply-templates/>
    </xsl:element>
    </xsl:template>

    </xsl:stylesheet>


    InPut XML

    <root><title>Solar System</title></root>

    Continue reading...

Compartilhe esta Página