4

I would like to create an xml file that can resemble something like this example

<Company>
  <Employee>
      <FirstName>Tanmay</FirstName>
      <LastName>Patil</LastName>
      <ContactNo>1234567890</ContactNo>
      <Email>tanmaypatil@xyz.com</Email>
      <Address>
        <place>
            <City>
                <CityName>
                   Bangalore 
                </CityName>
            </City>
            <State>Karnataka</State>
            <Zip>560212</Zip>
        </place>
      </Address>
  </Employee>
</Company>

I a using ElementTree and from what I have researched the only way to add a subelement is by doing

import xml.etree.cElementTree as ET

root = ET.Element("Company")
doc = ET.SubElement(root, "Employee")

I am wondering if there is anyway to specify a path that would make all the subelements such as

ET.SubElement("Employee/Address/place/City/CityName")

I found a similar question How to create multiple sub element under a root element in XML using python?. But that refers to creating multiple Employees and not creating subelements from a path.

The other questions that i have found on stack over flow refer to creating basic xml documents that do not go past one or two levels and the answers suggest having multiple .SubElement lines which makes sense for that amount of levels.

I have only used the employee example for demonstration purposes. The actual xml I need to create will have ~ 12 subelements of root and then those 12 subelements will have ~11 sub elements of their own. Any suggestions would be much appreciated.

Millicent
  • 86
  • 6

1 Answers1

1

You could create a simple function which iterates over the path:

import xml.etree.ElementTree as ET
# only used for pretty printing
import xml.dom.minidom

def create_subelements_from_path(root: ET.Element, path: str):
    for tag in path.split("/"):
        root = ET.SubElement(root,tag)

company = ET.Element("Company")
create_subelements_from_path(company, "Employee/Address/place/City/CityName")

# pretty print generated XML
print(xml.dom.minidom.parseString(ET.tostring(company)).toprettyxml())

Output:

<?xml version="1.0" ?>
<Company>
        <Employee>
                <Address>
                        <place>
                                <City>
                                        <CityName/>
                                </City>
                        </place>
                </Address>
        </Employee>
</Company>
M4C4R
  • 356
  • 4
  • 13
  • You don't need minidom. ElementTree has `indent()`: https://stackoverflow.com/a/68618047/407651 – mzjn Apr 30 '23 at 06:55