Search code examples
pythonxmlcsvscripting

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.


Solution

  • If the structure of CSV/XML file is simple you can use csv module and construct the string directly (for more complicated scenarios I recommend lxml/bs4 modules):

    import csv
    
    with open("your_data.csv", "r") as f:
        reader = csv.reader(f)
        header = next(reader)
        data = list(reader)
    
    out = ["<login>"]
    for line in data:
        s = " ".join(f'{k}="{v}"' for k, v in zip(header, line))
        out.append(f"\t<entry {s} />")
    out.append("</login>")
    
    print(*out, sep="\n")
    

    Prints:

    <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>