Right now I've hard coded the whole xml file in my python script and just doing out.write(), but now it's getting harder to manage because i have multiple types of xml file.
What is the easiest and quickest way to setup templating so that I can just give the variable names amd filename?
Short answer is: You should be focusing, and dealing with, the data (i.e., python object) and not the raw XML
Basic story: XML is supposed to be a representation of some data, or data set. You don't have a lot of detail in your question about the type of data, what it represents, etc, etc -- so I'll give you some basic answers.
Python choices: BeautifulSoup, lxml and other python libraries (ElementTree, etc.), make dealing with XML more easy. They let me read in, or write out, XML data much more easily than if I'd tried to work directly with the XML in raw form.
In the middle of those 2 (input,output) activities, my python program is dealing with a nice python object or some kind of parse tree I can walk. You can read data in, create an object from that string, manipulate it and write out XML.
Other choice, Templates: OK -- maybe you like XML and just want to "template" it so you can populate it with the data.
You might be more comfortable with this, if you aren't really manipulating the data -- but just representing it for output. And, this is similar to the XML strings you are currently using -- so may be more familiar.
Use Cheetah, Jinja, or other template libraries to help. Make a template for the XML file, using that template language.
For example, you just read a list of books from a file or database table. You would pass this list of book objects to the template engine, with a template, and then tell it to write out your XML output.
Example template for these book objects:
<?xml version="1.0"?>
<catalog>
{% for object in object_list %}
<book id="{{ object.bookID }}">
<author>{{ object.author_name }}</author>
<title>{{ object.title }}</title>
<genre>{{ object.genre }}</genre>
<price>{{ object.price }}</price>
<publish_date>{{ object.pub_date }}</publish_date>
<description>{{ object.description }}</description>
</book>
{% endfor %}
</catalog>
</xml>
The template engine would loop through the "object_list" and output a long XML file with all your books. That would be much better than storing raw XML strings, as you currently are.
This makes the update & modification of the display of XML separate from the data, data storage, and data manipulation -- making your life easier.
Two choices.
A template tool, for example Jinja2.
Build the DOM object. Not as bad as it sounds. ElementTree has a pleasant factory for building XML tags and creating the necessary structure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With