0

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>
2
  • 1
    Review how to use a loop. Your loop creates the same file for one invoice over and over again. Commented Jul 20, 2018 at 20:25
  • Simple run XSLT demo fiddle. Python's lxml module can run XSLT scripts. Commented Jul 20, 2018 at 21:43

1 Answer 1

1

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')
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Elvio Martinelli! :D

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.