简体   繁体   中英

Transferring Excel data to XML

I'm new to handeling XML in python so be easy on me. i've been trying transfer my excel data to an xml file that looks like so:

<?xml version="1.0" encoding="UTF-8"?>
<xml>
    <shelter>
        <adress>..</adress>
        <code>...</code>
        <neighborhood>..</neighborhood>
    </shelter>
    <shelter>
        <adress>...</adress>
        <code>...</code>
        <neighborhood>...</neighborhood>
    </shelter>
</xml>

my excel spread sheet looks like so:

在此处输入图片说明

Rather simple right? I tried a couple of methodes on excel also i tried to write a script to do but cant seem to make it work. Any ideas? Thanks a lot!

If this is just a one-time transformation you can use the CONCATENATE function to create the content of your XML. Put this formula in the D column for all rows:

=CONCATENATE("<shelter><adress>",A2,"</adress><code>",B2,"</code><neighborhood>",C2,"</neighborhood></shelter>")

Then copy the text to a new file, add the appropriate XML tags on the first and last line and you are done.

If you need to do this in Python, save the file as CSV such that you have something like (note that the header line is removed from this file):

adress1,1,n1
adress2,2,n1
adress3,3,n1 

Then you can use the following Python script to get the desired output:

print '<?xml version="1.0" encoding="UTF-8"?>'
with open('test.csv','r') as f:
    for x in f:
        splitted = x.split(',')
        print """
  <shelter>
    <adress>{0}</address>
    <code>{1}</code>
    <neighborhood>{2}</neighborhood>
  </shelter>""".format(x[0],x[1],x[2])
print '</xml>'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM