Skip to content

Instantly share code, notes, and snippets.

@csghone
Created November 6, 2019 04:53
Show Gist options
  • Select an option

  • Save csghone/3dee37f7a7c93f5f784d92d18cd14e4f to your computer and use it in GitHub Desktop.

Select an option

Save csghone/3dee37f7a7c93f5f784d92d18cd14e4f to your computer and use it in GitHub Desktop.
from mako.template import Template
from mako.lookup import TemplateLookup
from mako import exceptions
from lxml import etree
def get_pretty_xml(xml_string, xml_declaration=True):
parser = etree.XMLParser(remove_blank_text=True, recover=True)
root = etree.fromstring(xml_string, parser)
pretty_xml = etree.tostring(
root,
pretty_print=True,
encoding="utf-8",
xml_declaration=xml_declaration
)
return pretty_xml.decode()
def generate_xml(**kwargs):
template_file = kwargs["template_file"]
template_def_name = kwargs["template_def_name"]
xml_params = kwargs["xml_params"]
out_file = kwargs["out_file"]
template_lookup = TemplateLookup(directories=["."])
cur_template = Template(
filename=template_file,
lookup=template_lookup
)
xml_string = cur_template.get_def(template_def_name).render(**xml_params)
root = etree.fromstring(
xml_string.replace("&", "&").replace("&", "&"),
parser=etree.XMLParser(remove_blank_text=True)
)
if not os.path.exists(os.path.dirname(out_file)):
if not os.path.dirname(out_file) == "":
os.makedirs(os.path.dirname(out_file))
print(get_pretty_xml(etree.tostring(root)).strip(), file=open(out_file, mode="w+"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment