Advertisement
Python253

xml2html

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