Advertisement
Python253

xml2txt

Mar 16th, 2024
586
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.23 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: xml2txt.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9. This script converts an XML file (.xml) to a text file (.txt).
  10. It extracts the text content of each element in the XML and writes it to the text file.
  11.  
  12. Requirements:
  13. - Python 3.x
  14.  
  15. Usage:
  16. 1. Save this script as 'xml2txt.py'.
  17. 2. Ensure your XML file ('example.xml') is in the same directory as the script.
  18. 3. Run the script.
  19. 4. The converted text file ('xml2txt.txt') will be generated in the same directory.
  20.  
  21. Note: Adjust the 'xml_filename' and 'txt_filename' variables in the script as needed.
  22. """
  23.  
  24. import xml.etree.ElementTree as ET
  25.  
  26. def xml_to_txt(xml_filename, txt_filename):
  27.     tree = ET.parse(xml_filename)
  28.     root = tree.getroot()
  29.  
  30.     with open(txt_filename, 'w') as txtfile:
  31.         for element in root.iter():
  32.             if element.text:
  33.                 txtfile.write(element.text + '\n')
  34.  
  35. if __name__ == "__main__":
  36.     # Set the filenames for the XML and text files
  37.     xml_filename = 'example.xml'
  38.     txt_filename = 'xml2txt.txt'
  39.  
  40.     # Convert the XML to a text file
  41.     xml_to_txt(xml_filename, txt_filename)
  42.  
  43.     print(f"Converted '{xml_filename}' to '{txt_filename}'.")
  44.  
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement