Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a csv file to add details to xml file

Ned help to parse a csv file which has following details to xml file

csv file is in the following format:

name,ip,timeout
domain\user1,10.119.77.218,9000
domain\user2,2.80.189.26,9001
domain\user3,4.155.10.110,9002
domain\user4,9.214.119.86,9003
domain\user5,4.178.187.27,9004
domain\user6,3.76.178.117,9005

The above details from csv needs to be added to XML file which has the following format:

<login>
      <entry name="domain\user1" ip="10.119.77.218" timeout="9000"/>
      <entry name="domain\user2" ip="2.80.189.26" timeout="9001"/>
      <entry name="domain\user11" ip="4.155.10.110" timeout="12000"/>
      ...
</login>

Need some script because there are tones of files which needs to be converted. I tried the following tool: https://www.convertcsv.com/csv-to-xml.htm

But the above tool converts individual row to separate entry which is not needed. Looking for your feedback. Thank you.

like image 550
deep Avatar asked Nov 19 '25 15:11

deep


1 Answers

If you have data that should be XML-escaped, here's a simple starter for using the standard xml.etree module:

import csv
import xml.etree.ElementTree as ET

root = ET.Element("login")
with open("input.csv", newline="") as f:
    reader = csv.DictReader(f)
    for row in reader:
        ET.SubElement(root, "entry", row)

tree = ET.ElementTree(root)
ET.indent(tree)
tree.write("output.xml")

ET.SubElement(root, "entry", row) does most of the real work, along with Python's DictReader: each row dict becomes the attributes on an entry node:

<login>
  <entry name="domain\user1" ip="10.119.77.218" timeout="9000" />
  <entry name="domain\user2" ip="2.80.189.26" timeout="9001" />
  <entry name="domain\user3" ip="4.155.10.110" timeout="9002" />
  <entry name="domain\user4" ip="9.214.119.86" timeout="9003" />
  <entry name="domain\user5" ip="4.178.187.27" timeout="9004" />
  <entry name="domain\user6" ip="3.76.178.117" timeout="9005" />
</login>
like image 183
Zach Young Avatar answered Nov 21 '25 05:11

Zach Young