Skip to content

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>
  1. Install the following programs and libraries:

    Terminal window
    sudo apt install libxml2-dev libxslt1-dev python3-lxml
  2. Create the following Python script populate-xml.py:

    #!/usr/bin/python3
    # coding: utf8
    from lxml import etree
    root = 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 = P
    list = etree.SubElement(topic, 'ul')
    for v in versions:
    version = etree.SubElement(list, 'li')
    version.text = v
    try:
    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.2
    Topic//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)
  3. Make the script executable, then run it:

    Terminal window
    chmod +x populate-xml.py
    ./populate-xml.py

    The modele.dita file is created and contains the desired data.

This approach minimizes the risk of errors and reduces the effort involved in updating.