Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add incremental number to element in XML file (Python)

I’m new with Python and I’ve got this issue on my hands that I cannot seem to find a way to resolve it.

I have this XML file where I want to add an incremental number (1,2,3,4,5, etc…) for each <ID> element found in the XML file, at the moment the value is always 0.

Here’s a snapshot of the XML file:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<?xml version='1.0' encoding='UTF-8'?>
<PlaceData>
  <PlaceRecord>
    <ID>0</ID>
    <Name>Place 1</Name>
    <ID1>1190967</ID1>
  </PlaceRecord>  
  <PlaceRecord>
    <ID>0</ID>
    <Name>Place 2</Name>
    <ID1>1191672</ID1>
  </PlaceRecord>  
  <PlaceRecord>
    <ID>0</ID>
    <Name>Place 3</Name>
    <ID1>1187415</ID1>
  </PlaceRecord>
</PlaceData>

Here’s the code I have so far, adding "0" to all elements:

import xml.etree.ElementTree as ET

placesxml = ET.parse("places.xml")
placesxml_data = placesxml.getroot()

for element in placesxml_data:
    element.find('ID').text = '0'

placesxml.write("places.xml", encoding='UTF-8', xml_declaration=True)

What I would like to have is an incremental value added to each <ID> element:

<?xml version='1.0' encoding='UTF-8'?>
<PlaceData>
  <PlaceRecord>
    <ID>1</ID>
    <Name>Place 1</Name>
    <ID1>1190967</ID1>
  </PlaceRecord>  
  <PlaceRecord>
    <ID>2</ID>
    <Name>Place 2</Name>
    <ID1>1191672</ID1>
  </PlaceRecord>  
  <PlaceRecord>
    <ID>3</ID>
    <Name>Place 3</Name>
    <ID1>1187415</ID1>
  </PlaceRecord>
</PlaceData>

I’m sorry if this is too basic to ask but like I said, I’m very new at this and would love to know how I can do this for other projects I am working on.

Hope I provided all the info needed, appreciate any help!

>Solution :

Tried the increment approach?

import xml.etree.ElementTree as ET

placesxml = ET.parse("places.xml")
placesxml_data = placesxml.getroot()

i_id = 0
for element in placesxml_data:
    element.find('ID').text = str(i_id)
    i_id += 1

placesxml.write("places.xml", encoding='UTF-8', xml_declaration=True)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading