Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- # Filename: xml2csv.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- Description:
- This script converts an XML file (.xml) to a CSV file (.csv).
- It extracts data from specific elements in the XML and writes it to the CSV file.
- Requirements:
- - Python 3.x
- Usage:
- 1. Save this script as 'xml2csv.py'.
- 2. Ensure your XML file ('example.xml') is in the same directory as the script.
- 3. Update the 'your_element_path' and field names in the script based on your XML structure.
- 4. Run the script.
- 5. The converted CSV file ('xml2csv.csv') will be generated in the same directory.
- Note: Adjust the 'xml_file' and 'csv_file' variables in the script as needed.
- """
- import xml.etree.ElementTree as ET
- import csv
- def xml_to_csv(xml_file, csv_file):
- tree = ET.parse(xml_file)
- root = tree.getroot()
- with open(csv_file, 'w', newline='') as csvfile:
- csvwriter = csv.writer(csvfile)
- # Update 'your_element_path' and field names based on your XML structure
- for element in root.findall('.//your_element_path'):
- # Extract data and write to CSV
- csvwriter.writerow([element.find('field1').text, element.find('field2').text, ...])
- if __name__ == "__main__":
- # Set the filenames for the XML and CSV files
- xml_file = 'example.xml'
- csv_file = 'xml2csv.csv'
- # Convert the XML to a CSV file
- xml_to_csv(xml_file, csv_file)
- print(f"Converted '{xml_file}' to '{csv_file}'.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement