{"id":95,"date":"2024-02-28T04:31:14","date_gmt":"2024-02-28T04:31:14","guid":{"rendered":"http:\/\/localhost\/tfcom_wp\/2024\/02\/28\/add-subelement-xml\/"},"modified":"2025-06-30T02:20:00","modified_gmt":"2025-06-30T02:20:00","slug":"add-subelement-xml","status":"publish","type":"post","link":"https:\/\/www.tech-freaks.com\/python\/add-subelement-xml.html","title":{"rendered":"Multiple ways to add sub elements to XML elements using Python"},"content":{"rendered":"<p style=\"text-align: left;\">Recently, I have been working on manipulating xmls and csvs using Python. I was amazed by how quick and easy it is manipulate these files in Python. In this article I cover the flexibility of the python and xml.etree.ElementTree API. Let us jump into it.<\/p>\n<h4 style=\"text-align: left;\">Problem<\/h4>\n<p style=\"text-align: left;\">Given a dictionary of words and meaning in multiple language. We want to manipulate the xml and add another meaning in French language for the word <em>beauty.\u00a0<\/em><\/p>\n<p><!--more--><\/p>\n<pre class=\"language-markup\"><code>&lt;dictionary&gt;\r\n    &lt;definition&gt;\r\n        &lt;word lang=\"en-US\"&gt;beauty&lt;\/word&gt;\r\n        &lt;meaning lang=\"en-US\"&gt;\r\n            a combination of qualities, such as shape, color, or form, that pleases the aesthetic senses, especially the sight.\r\n        &lt;\/meaning&gt;\r\n    &lt;\/definition&gt;\r\n&lt;\/dictionary&gt;<\/code><\/pre>\n<h4 style=\"text-align: left;\">Approach 1<\/h4>\n<p style=\"text-align: left;\">The simplest approach is to find \/ reach the element of <em>definition. <\/em>Then add a sub-element <em>meaning\u00a0<\/em>to the <em>definition. <\/em>This would look something like below.<\/p>\n<pre class=\"language-python\"><code>import xml.etree.ElementTree as ET\r\n\r\n# Parse the XML file\r\ntree = ET.parse('sample.xml')\r\nroot = tree.getroot()\r\n\r\nbeauty_meaning_fr = \"La beaut\u00e9 est l'harmonie des formes et des couleurs qui \u00e9voque un sentiment d'\u00e9merveillement et d'admiration.\"\r\n\r\ndef_elements = root.findall('definition')\r\n\r\nfor definition in def_elements:\r\n    word = definition.find('word')\r\n    if word.text == 'beauty':\r\n        new_meaning = ET.SubElement(definition, 'meaning')\r\n        new_meaning.text = beauty_meaning_fr\r\n        new_meaning.set('lang', 'fr-FR')\r\n\r\ntree.write('output.xml')<\/code><\/pre>\n<p style=\"text-align: left;\">This approach works great and provides the desired output.<\/p>\n<pre class=\"language-markup\"><code>&lt;dictionary&gt;\r\n    &lt;definition&gt;\r\n        &lt;word lang=\"en-US\"&gt;beauty&lt;\/word&gt;\r\n        &lt;meaning lang=\"en-US\"&gt;\r\n            a combination of qualities, such as shape, color, or form, that pleases the aesthetic senses, especially the sight.\r\n        &lt;\/meaning&gt;\r\n    &lt;meaning lang=\"fr-FR\"&gt;La beaut&amp;#233; est l'harmonie des formes et des couleurs qui &amp;#233;voque un sentiment d'&amp;#233;merveillement et d'admiration.&lt;\/meaning&gt;&lt;\/definition&gt;\r\n&lt;\/dictionary&gt;<\/code><\/pre>\n<p style=\"text-align: left;\">However, when I was working on my real-life problem, the above code did not add the <em>meaning <\/em>element for some reason. Hence, I started looking for another approach to solve my issue.<\/p>\n<h3 style=\"text-align: left;\">Approach 2<\/h3>\n<p style=\"text-align: left;\">Another option is to add a new element <em>meaning<\/em>, instead of a sub-element. Of course, the element will then need to added to another element. To achieve our requirement, we need to reach the <em>definition <\/em>element and insert or append the <em>meaning<\/em> element that we initially created. The below code summarizes this approach:<\/p>\n<pre class=\"language-python\"><code>import xml.etree.ElementTree as ET\r\n\r\n# Parse the XML file\r\ntree = ET.parse('sample.xml')\r\nroot = tree.getroot()\r\n\r\nbeauty_meaning_fr = \"La beaut\u00e9 est l'harmonie des formes et des couleurs qui \u00e9voque un sentiment d'\u00e9merveillement et d'admiration.\"\r\n\r\ndef_elements = root.findall('definition')\r\n\r\nfor definition in def_elements:\r\n    word = definition.find('word')\r\n    if word.text == 'beauty':\r\n        new_meaning = ET.Element(\"meaning\")\r\n        new_meaning.text = beauty_meaning_fr\r\n        new_meaning.set('lang', 'fr-FR')\r\n        definition.append(new_meaning)\r\n\r\ntree.write('output1.xml')<\/code><\/pre>\n<p style=\"text-align: left;\">The code works as expected and generates the output similar to that of approach 1.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Recently, I have been working on manipulating xmls and csvs using Python. I was amazed by how quick and easy [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":true,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[8],"tags":[],"class_list":["post-95","post","type-post","status-publish","format-standard","hentry","category-python"],"_links":{"self":[{"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/posts\/95","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/comments?post=95"}],"version-history":[{"count":1,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/posts\/95\/revisions"}],"predecessor-version":[{"id":131,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/posts\/95\/revisions\/131"}],"wp:attachment":[{"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/media?parent=95"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/categories?post=95"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/tags?post=95"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}