Advertisement
Python253

xml2json

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