Auto-insert data into a DITA XML file
We want to automate the generation of the following DITA file:
<?xml version = "1.0" encoding = "utf-8"?><!DOCTYPE topic PUBLIC "-//OASIS//DTD DITA 1.2 Topic//EN" "/usr/share/dita-ot/dtd/technicalContent/dtd/topic.dtd"><topic id="products-and-versions"> <title>Products and versions</title> <body> <p>Dianthus</p> <ul> <li>1.0</li> <li>1.5</li> <li>2.3</li> </ul> <p>Geum</p> <ul> <li>1.0</li> <li>1.5</li> <li>2.3</li> </ul> <p>Prunus</p> <ul> <li>1.0</li> <li>1.5</li> <li>2.3</li> </ul> </body></topic>-
Install the following programs and libraries:
Terminal window sudo apt install libxml2-dev libxslt1-dev python3-lxml -
Create the following Python script
populate-xml.py:#!/usr/bin/python3# coding: utf8from lxml import etreeroot = etree.Element('topic')root.set('id', 'produits-et-versions')title = etree.SubElement(root, 'title')title.text = "Produits et versions"topic = etree.SubElement(root, 'body')products = ['dianthus', 'geum', 'prunus']versions = ['1.0', '1.5', '2.3']for p in products:P = str.capitalize(p)product = etree.SubElement(topic, 'p')product.text = Plist = etree.SubElement(topic, 'ul')for v in versions:version = etree.SubElement(list, 'li')version.text = vtry:with open('modele.dita', 'w') as file:file.write('<?xml version = "1.0" encoding = "utf-8"?>\n')file.write('''<!DOCTYPE topic PUBLIC "-//OASIS//DTD DITA 1.2Topic//EN""/usr/share/dita-ot/dtd/technicalContent/dtd/topic.dtd">\n''')file.write(etree.tostring(root, pretty_print=True).decode('utf-8'))except IOError:print('Erreur d\'écriture')exit(1) -
Make the script executable, then run it:
Terminal window chmod +x populate-xml.py./populate-xml.pyThe
modele.ditafile is created and contains the desired data.
This approach minimizes the risk of errors and reduces the effort involved in updating.