Concatenate values from XML file in Python -


i try concatenate xml attributes, takes first pair, , starts attributes new item. make sense when read through file.

import os, csv xml.etree import elementtree   file_name = 'data.xml' full_file = os.path.abspath(os.path.join('xml', file_name)) dom = elementtree.parse(full_file)  open('output.csv', 'w', newline="") f:      writer = csv.writer(f)     writer.writerow(['fruitnumber', 'categorynumber', 'group', 'attributevaluename'])    d in dom.findall('//item'):     part = d.find('.//item-number').text     name = d.find('.//name').text     value = d.find('.//value').text      writer.writerow([part, '' , '', name + ":" + value]) 

here xml file:

<?xml version="1.0"?> <all> <items> <item> <item-number>449</item-number> <attributes> <attribute> <name>fruit</name> <value>lemon</value> </attribute> <attribute> <name>color</name> <value>yellow</value> </attribute> </attributes> </item> <item> <item-number>223</item-number> <attributes> <attribute> <name>fruit</name> <value>orange</value> </attribute> <attribute> <name>color</name> <value>orange</value> </attribute> </attributes> </item> </items> </all> 

here get:

fruitnumber categorynumber  group   attributevaluename 449                                 fruit:lemon 223                                 fruit:orange 

here trying get:

fruitnumber categorynumber  group   attributevaluename 449                                 fruit:lemon│color:yellow 223                                 fruit:orange│color:orange 

thanks in advance!!!

you're reading first attribute of each item. need additionally search attributes under item, collect them, format them require when writing row:

import os, csv xml.etree import elementtree   file_name = 'data.xml' full_file = os.path.abspath(os.path.join('xml', file_name)) dom = elementtree.parse(full_file)  open('output.csv', 'w', newline="") f:      writer = csv.writer(f)     writer.writerow(['fruitnumber', 'categorynumber', 'group', 'attributevaluename'])      d in dom.findall('.//item'):         part = d.find('.//item-number').text         l = []         in d.findall('.//attribute'):             name = a.find('.//name').text             value = a.find('.//value').text             l.append('{}:{}'.format(name,value))         writer.writerow([part, '' , '', '|'.join(l)]) 

output

fruitnumber,categorynumber,group,attributevaluename 449,,,fruit:lemon|color:yellow 223,,,fruit:orange|color:orange 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -