Created
March 21, 2022 23:24
-
-
Save swhume/b5bd90f277c8f78438b1e3aa19bdc305 to your computer and use it in GitHub Desktop.
This file contains 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 lxml.etree as ET | |
import argparse | |
import os | |
""" | |
Example Cmd-line Args: | |
example: -x ./data/some.xml -o ./data/some.html -s ./data/transform.xslt | |
""" | |
def transform_xml_to_html(args): | |
xml_tree = ET.parse(args.xml_file) | |
xslt = ET.parse(args.xslt_file) | |
transform = ET.XSLT(xslt) | |
html_dom = transform(xml_tree) | |
html_file_name = _set_html_file_name(args) | |
with open(html_file_name, "w") as html_file: | |
html_string = ET.tostring(html_dom, pretty_print=True) | |
html_file.write(html_string.decode("utf-8")) | |
def _set_html_file_name(args): | |
if args.html_file: | |
return args.html_file | |
else: | |
path_and_file, ext = os.path.splitext(args.xml_file) | |
return path_and_file + "." + "html" | |
def set_cmd_line_args(): | |
""" | |
get the command-line arguments needed to convert the XML input file into HTML using XSLT | |
:return: return the argparse object with the command-line parameters | |
""" | |
parser = argparse.ArgumentParser() | |
parser.add_argument("-x", "--xml", help="path and file name of the xml file", required=True, | |
dest="xml_file") | |
parser.add_argument("-o", "--out", help="path and file name of HTML file to create", required=False, | |
dest="html_file") | |
parser.add_argument("-s", "--xslt", help="path and file name of the stylesheet", required=True, | |
dest="xslt_file") | |
args = parser.parse_args() | |
return args | |
def main(): | |
""" main driver method that generates HTML from XML using XSLT """ | |
args = set_cmd_line_args() | |
transform_xml_to_html(args) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment