'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:
<?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 1:[1]
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)
Solution 2:[2]
You might enumerate for this task following way, replace
for element in placesxml_data:
element.find('ID').text = '0'
using
for inx, element in enumerate(placesxml_data):
element.find('ID').text = str(inx)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Numan Ijaz |
| Solution 2 | Daweo |
