Home > Net >  How to add custom data to my entire xml data?
How to add custom data to my entire xml data?

Time:06-27

I am trying add the custom data across all my xml

Data:

<?xml version='1.0' encoding='utf-8'?>
<data>
  <row>
    <index>0</index>
    <price>$5.95</price>
    <name>Belgian Waffles</name>
    <desc>Two of our famous Belgian Waffles with plenty of real maple syrup</desc>
    <calories>650</calories>
  </row>
  <row>
    <index>1</index>
    <price>$7.95</price>
    <name>Strawberry Belgian Waffles</name>
    <desc>Light Belgian waffles covered with strawberries and whipped cream</desc>
    <calories>900</calories>
  </row>
  <row>
    <index>2</index>
    <price>$8.95</price>
    <name>Berry-Berry Belgian Waffles</name>
    <desc>Light Belgian waffles covered with an assortment of fresh berries and whipped cream</desc>
    <calories>900</calories>
  </row>
  <row>
    <index>3</index>
    <price>$4.50</price>
    <name>French Toast</name>
    <desc>Thick slices made from our homemade sourdough bread</desc>
    <calories>600</calories>
  </row>
  <row>
    <index>4</index>
    <price>$6.95</price>
    <name>Homestyle Breakfast</name>
    <desc>Two eggs, bacon or sausage, toast, and our ever-popular hash browns</desc>
    <calories>950</calories>
  </row>
</data>

My code:

import xml.etree.ElementTree as ET
parse_xml = ET.parse('/content/sample_data/xyz.xml')
get_root_element = parse_xml.getroot()
ET.SubElement(get_root_element[0],'FID')

for data in get_root_element:
  customtext = 'ABC'
  data.text = str(customtext)
parse_xml.write('abc.xml')

I have written : ET.SubElement(get_root_element[0],'FID') -> It add data to only first indexing.

I want the same to be added to all the indexing?

CodePudding user response:

If you only want to add a child object to the row elements, the following code would work.

import xml.etree.ElementTree as ET
parse_xml = ET.parse('xyz.xml')
get_root_element = parse_xml.getroot()
i = 0
while True:
    try:
        ET.SubElement(get_root_element[i],'FID')
        i  = 1
    except:
        break
ET.dump(parse_xml)

CodePudding user response:

Thanks for the solution : @Efe

This worked like a charm for me

My code :

import xml.etree.ElementTree as ET
parse_xml = ET.parse('/content/sample_data/xyz.xml')
get_root_element = parse_xml.getroot()

for idx,record in enumerate(get_root_element):
  ET.SubElement(get_root_element[idx],'FID')

for data in get_root_element.iter('FID'):
  customtext = 'ABC'
  data.text = str(customtext)
parse_xml.write('/content/sample_data/abc.xml')
  • Related