Fast and easy way to template xml files in python

Right now I have hardcoded the whole xml file in my python script and just executed out.write (), but now it is getting harder to manage because I have several types of xml file.

What is the easiest and fastest way to set up templates so that I can just specify the variable names amd filename?

+3
source share
5 answers

You asked for the easiest and fastest, so see this post: http://blog.simonwillison.net/post/58096201893/simpletemplates

If you want something smarter, look here .

0
source

Two options.

  • , Jinja2.

  • DOM. , . ElementTree factory XML .

+3

xml.dom.minidom

xml.dom.minidom - Document Object Model. , DOM, .

DOM API xml.dom, DOM Element, XML, Node.writexml. , DOM, , .

pythonic ElementTree.

- , . .

ElementTree Python XML ElementTree.dump() ElementTree.tostring()

+3

YAPTU Palmer yaptoo , - , , . .

+1

:. (.. python), XML

: , XML . , , , .. .. - .

Python: BeautifulSoup, lxml python (ElementTree ..) XML. XML- , XML .

(, ) python python - , . , , XML.

, : - , XML " ", .

, , . XML, , - .

Cheetah, Jinja , . XML, .

, . , , , XML.

:

<?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 will go through the "object_list" and output a long XML file with all your books. This will be much better than storing raw XML strings, as you are now.

This makes updating and changing the display of XML separate from data, storing data and manipulating data - makes your life easier.

+1
source

Source: https://habr.com/ru/post/1711439/


All Articles