3r1c
3r1c

Reputation: 3

XML to XML in Python

The xml file contains many datas including some invoices. I would like to extract only the invoices from the xml file and create a new xml file that only contains the invoices.

I wrote a code that extract the invoices but when it comes to create a new xml file (with invoices) it only contains one invoice. How can i modify my code to create the xml file with all of the invoices.

Please help me to solve this problem.

My code: (bizonylat means invoice)

import os
import xml.etree.ElementTree as ET

utvonal = os.path.dirname(os.path.realpath(__file__))
xml_file = os.path.join(utvonal, 'xml\\01-K011116_K011169.xml') 
doc = ET.parse(xml_file).getroot()

for invoice in doc.findall('bizonylat'):
    invoices = ET.ElementTree(invoice).write('out.xml', 'utf8')

XML scheme:

<konyveles>
  <program>Kont&#xED;r FB </program>
  <verzio>1.12.2.8</verzio>
  <feladdatum>2014.01.26</feladdatum>
  <feladido>17:05:38</feladido>
  <cegnev>C&#xE9;g neve</cegnev>
  <felhasznalo>Tulajdonos</felhasznalo>
  <bizonylat>
    <bizonylatszam>V3</bizonylatszam>
    <biz_egyedi_id/>
    <konyv_dat>2013.01.24</konyv_dat>
    <teljesites_dat>2013.02.11</teljesites_dat>
    <esedekesseg_dat>2013.03.20</esedekesseg_dat>
    <partneradat/>
    <bizonylat_netto>628937,00</bizonylat_netto>
    <bizonylat_brutto>798750,00</bizonylat_brutto>
    <kontirozasok></kontirozasok>
  </bizonylat>
  <bizonylat>
    <bizonylatszam>V3</bizonylatszam>
    <biz_egyedi_id/>
    <konyv_dat>2013.01.24</konyv_dat>
    <teljesites_dat>2013.02.11</teljesites_dat>
    <esedekesseg_dat>2013.03.20</esedekesseg_dat>
    <partneradat/>
    <bizonylat_netto>628937,00</bizonylat_netto>
    <bizonylat_brutto>798750,00</bizonylat_brutto>
    <kontirozasok></kontirozasok>
  </bizonylat>
</konyveles>

Upvotes: 0

Views: 147

Answers (1)

emartinelli
emartinelli

Reputation: 1047

If you want a well-formatted XML you will need a root element in your document, then you can add all your elements to the root and save to your file.

root = ET.Element('root')
root.extend(doc.findall('bizonylat'))
ET.ElementTree(root).write('out.xml', 'utf8')

Upvotes: 1

Related Questions