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>

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.

Answer from joej on Stack Overflow
Top answer
1 of 5
6

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>

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.

2 of 5
4

Two choices.

  1. A template tool, for example Jinja2.

  2. Build the DOM object. Not as bad as it sounds. ElementTree has a pleasant factory for building XML tags and creating the necessary structure.

๐ŸŒ
GitHub
github.com โ€บ jackrosenthal โ€บ kajiki
GitHub - jackrosenthal/kajiki: Python XML-based template engine with Genshi-like syntax and Jinja-style blocks
>>> import kajiki >>> Template = kajiki.XMLTemplate('''<html> ... <head><title>$title</title></head> ... <body> ... <h1>$title</h1> ... <ul> ... <li py:for="x in range(repetitions)">$title</li> ... </ul> ... </body> ... </html>''') >>> print(Template(dict(title='Kajiki is teh awesome!', repetitions=3)).render()) <html> <head><title>Kajiki is teh awesome!</title></head> <body> <h1>Kajiki is teh awesome!</h1> <ul> <li>Kajiki is teh awesome!</li><li>Kajiki is teh awesome!</li><li>Kajiki is teh awesome!</li> </ul> </body> </html>
Starred by 50 users
Forked by 17 users
Languages ย  Python 92.6% | HTML 7.4% | Python 92.6% | HTML 7.4%
๐ŸŒ
Python
wiki.python.org โ€บ moin โ€บ Templating
Templating - Python Wiki
Evoque page on pypi - managed eval-based full-featured templating engine, for Python 2.4, 2.5, 2.6 and 3.0, features such as unicode, dynamic overlays, format-extensible automatic quoting, in-process sandbox, et cetera, while still remaining small, simple and extremely fast -- performance benchmarks show it to be more or less as fast as Mako, and faster on simpler templates. HRL (HTML Redemption Language) - Powerful macro preprocessor for HTML; macros can embed arbitrary Python code. ( 2010-07-04, Officially discontinued) Genshi - XML-based templating engine, used in the popular python tool trac.
๐ŸŒ
pytz
pythonhosted.org โ€บ Genshi โ€บ xml-templates.html
Genshi: Genshi XML Template Language
Templates are XML files of some kind (such as XHTML) that include processing directives (elements or attributes identified by a separate namespace) that affect how the template is rendered, and template expressions that are dynamically substituted by variable data. See Genshi Templating Basics for general information on embedding Python code in templates.
๐ŸŒ
GitHub
github.com โ€บ malthe โ€บ chameleon
GitHub - malthe/chameleon: Fast HTML/XML template engine for Python ยท GitHub
Chameleon is an HTML/XML template engine for Python.
Starred by 183 users
Forked by 67 users
Languages ย  Python
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ xml.etree.elementtree.html
xml.etree.ElementTree โ€” The ElementTree XML API
January 29, 2026 - Source code: Lib/xml/etree/ElementTree.py The xml.etree.ElementTree module implements a simple and efficient API for parsing and creating XML data. Tutorial: This is a short tutorial for using xml....
Find elsewhere
๐ŸŒ
Scraping Robot
scrapingrobot.com โ€บ blog โ€บ create-xml-with-python
Create XML With Python: A Roadmap to Parsing With Python
February 24, 2024 - Pull parsers combine elements of both DOM and SAX to create XML with Python. They provide an API that allows the application to pull, or request, the next event from the parser. They let a program ask for pieces of an XML document one by one, whenever itโ€™s ready to handle them.
๐ŸŒ
Full Stack Python
fullstackpython.com โ€บ template-engines.html
Template Engines - Full Stack Python
Template engines provide programmatic output of formatted string content such as HTML, XML or PDF.
๐ŸŒ
Evanjones
evanjones.ca โ€บ software โ€บ simplexmlparse.html
SimpleXMLParse: XML to Python Objects and Back Again (evanjones.ca)
April 16, 2006 - SimpleXMLParse uses a template to build Python objects for XML elements. To create a template, you take an example document and annote it to describe which elements and attributes are required and which are optional.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ create-xml-documents-using-python
Create XML Documents using Python - GeeksforGeeks
May 10, 2020 - Element() function creates a standard node, SubElement() function attaches a new node to a parent node, and Comment() function creates a node that serializes using XML's comment syntax. The attribute values can be configured one at a time withset() (as with the root node), or all at once by passing a dictionary to the node factory(as with each group and podcast node). ... In this article, we will be learning how to create PDFs in Python.
๐ŸŒ
Graphisoft Community
community.graphisoft.com โ€บ graphisoft community (int) โ€บ developer hub โ€บ gdl
Solved: generating xml object via python - Graphisoft Community
September 24, 2024 - I have messed around with similar stuff in the past. I was using the lxml python package to create and modify the xml nodes from a decompiled gsm. I think you idea of using a template xml object, and then modify the parameters of that xml file and assign it a new name and guid sounds fairly straightforward.
Top answer
1 of 2
4

To create an XML document in Python, it seems easier to use the Yattag library.

from yattag import Doc

doc, tag, text = Doc().tagtext()

x = 2*5

with tag('personal', reference = "500.txt"):
    with tag('others:sequence'):
        doc.stag('feature', name = "Michael", age = str(x), dob = "15/10/1900")

print(doc.getvalue())

When run, the above code will generate the following XML:

<personal reference="500.txt">
  <others:sequence>
    <feature name="Michael" age="10" dob="15/10/1900" />
  </others:sequence>
</personal>

Note: Indentation was added to the example above for readability, as getvalue returns a single line without spaces between tags. To produce a formatted document, use the indent function.

2 of 2
3

Your template needs curly braces:

x=2*5
xmlTemplate="""
<personal reference="500.txt">
    <others:sequence>
        <feature:name="{name}" age="{age}" dob="{dob}"/>
    </others:sequence>
</personal>""".format(name='Michael', age=x, dob='15/10/1900')
print xmlTemplate

yields

<personal reference="500.txt">
    <others:sequence>
        <feature:name="Michael" age="10" dob="15/10/1900"/>
    </others:sequence>
</personal>

The format method replaces names in curly-braces. Compare, for example,

In [20]: 'cheese'.format(cheese='Roquefort')
Out[20]: 'cheese'

In [21]: '{cheese}'.format(cheese='Roquefort')
Out[21]: 'Roquefort'

I see you have lxml. Excellent. In that case, you could use lxml.builder to construct XML. This will help you create valid XML:

import lxml.etree as ET
import lxml.builder as builder
E = builder.E
F = builder.ElementMaker(namespace='http://foo', nsmap={'others':'http://foo'})

x = 2*5
xmlTemplate = ET.tostring(F.root(
    E.personal(
        F.sequence(
            E.feature(name='Michael',
                   age=str(x),
                   dob='15/10/1900')
            ), reference="500.txt")),
                          pretty_print=True)
print(xmlTemplate)

yields

<others:root xmlns:other="http://foo">
  <personal reference="500.txt">
    <others:sequence>
      <feature dob="15/10/1900" age="10" name="Michael"/>
    </others:sequence>
  </personal>
</others:root>

and this string can be parsed by lxml using:

doc = ET.fromstring(xmlTemplate)
print(doc)
# <Element {http://foo}root at 0xb741866c>
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ create-xml-documents-using-python
Create XML Documents using Python
Some best practices for creating XML documents using Python include: using indentation to improve readability; using appropriate namespaces; using unique element and attribute names; and using validating parsers to ensure the validity of the XML document.
๐ŸŒ
Google Groups
groups.google.com โ€บ g โ€บ django-users โ€บ c โ€บ pstcRaIAS6A
Parsing XML in the template? (New to Django and Python)
Each video > will have a different thumbnail and XML file to parse. As of right now > my "main_page" in my views.py file looks like this: > > def home_page(request): > template = get_template('home_page.html') > videos = Video.objects.all() videos_context = [ ] for v in videos:
๐ŸŒ
Opensource.com
opensource.com โ€บ resources โ€บ python โ€บ template-libraries
3 Python template libraries compared | Opensource.com
April 27, 2018 - Unlike Mako, which uses Python inline for logic inside your templates, Jinja2 uses its own syntax. Genshi is the third option I'll mention. It's really an XML tool which has a strong templating component, so if the data you are working with is already in XML format, or you need to work with formatting beyond a web page, Genshi might be a good solution for you.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 37110607 โ€บ python-write-a-new-xml-file-based-on-a-xml-template
Python: Write a new xml file based on a xml template - Stack Overflow
April 27, 2017 - Outputs ElementTree and element''' tree = ET.parse(name) root = tree.getroot() return tree, root if __name__ == "__main__": # Change and write the new xml tree, root = load_xml('template.xml') group = root.find('group') group.find('name').text = 'New' tree.write('new.xml') ... ElementTree in the core python doesn't seem to support CData section : 1, 2.