Advertisement
Python253

json_to_xml

Mar 14th, 2024
562
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.14 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: json_to_xml.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9. This script converts a JSON file (.json) to an XML file (.xml).
  10. It reads the JSON file and creates an XML file with the JSON content.
  11.  
  12. Requirements:
  13. - Python 3.x
  14.  
  15. Usage:
  16. 1. Save this script as 'json_to_xml.py'.
  17. 2. Ensure your JSON file ('example.json') is in the same directory as the script.
  18. 3. Run the script.
  19.  
  20. Note: Adjust the 'json_filename' and 'xml_filename' variables in the script as needed.
  21. """
  22. import json
  23. import xml.etree.ElementTree as ET
  24.  
  25. def json_to_xml(json_filename, xml_filename):
  26.     with open(json_filename, 'r') as jsonfile:
  27.         data = json.load(jsonfile)
  28.         root = ET.Element("root")
  29.         if "text_content" in data:
  30.             ET.SubElement(root, "element").text = data["text_content"]
  31.  
  32.         tree = ET.ElementTree(root)
  33.         tree.write(xml_filename)
  34.  
  35. if __name__ == "__main__":
  36.     json_filename = 'example.json'
  37.     xml_filename = 'json2xml.xml'
  38.     json_to_xml(json_filename, xml_filename)
  39.     print(f"Converted '{json_filename}' to '{xml_filename}'.")
  40.  
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement