Advertisement
Python253

xml2bin

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