Home > other >  How can I iterate the "<row></row>" tag in my XML file?
How can I iterate the "<row></row>" tag in my XML file?

Time:04-28

The below code will work just fine. However, the resulting xml will have each row tagged all the same for each record. I need this tag to be unique. My intent was to have the tag read <row 1></row 1>, <row 2></row 2>, ... I've commented out what I attempted but I get a type error when I try to run this in python. does anyone know a fix for this issue?

import csv

csvFile = 'BySystem.csv'
xmlFile = 'BySystem.xml'

csvData = csv.reader(open(csvFile))
xmlData = open(xmlFile, 'w')
xmlData.write('<?xml version="1.0"?>'   "\n")


rowNum = 0
for row in csvData:
    if rowNum == 0:
        tags = row
        # replace spaces w/ underscores in tag names
        for i in range(len(tags)):
            tags[i] = tags[i].replace(' ', '_')
    else: 
       #xmlData.write('<row '   rowNum   '>'   "\n")
        xmlData.write('<row>'   "\n")
        for i in range(len(tags)):
            xmlData.write('    '   '<'   tags[i]   '>' \
                            row[i]   '</'   tags[i]   '>'   "\n")
        #xmlData.write('</row '   rowNum   '>'   "\n")
        xmlData.write('</row>'   "\n")
            
    rowNum  =1

xmlData.write('</csv_data>'   "\n")
xmlData.close()

CodePudding user response:

rowNum is int, you can not simply concatenate str with int, either convert int to str before concatenation that is replace

xmlData.write('<row '   rowNum   '>'   "\n")
xmlData.write('</row '   rowNum   '>'   "\n")

using

xmlData.write('<row '   str(rowNum)   '>'   "\n")
xmlData.write('</row '   str(rowNum)   '>'   "\n")

or use one kind of string formatting, e.g. so-called f-string (requires python3.6 or newer)

xmlData.write(f'<row {rowNum}>\n')
xmlData.write(f'</row {rowNum}>\n')
  • Related