Advertisement
k98kurz

prettifyxml.py

Feb 21st, 2023
952
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.79 KB | Source Code | 0 0
  1. from sys import argv
  2. from xml.dom import minidom
  3.  
  4.  
  5. def usage(name: str):
  6.     print(f'usage: python {name} src_file_path [dst_file_path]')
  7.  
  8.  
  9. def prettify_xml(src_file_path: str) -> str:
  10.     """Reads the file and returns prettified xml string."""
  11.     dom = minidom.parse(src_file_path)
  12.     return dom.toprettyxml()
  13.  
  14.  
  15. def main(src_file_path: str, dst_file_path: str = None):
  16.     """Run as stand-alone tool."""
  17.     if src_file_path == dst_file_path:
  18.         print('src_file_path and dst_file_path must differ')
  19.         return
  20.  
  21.     pretty_xml_str = prettify_xml(src_file_path)
  22.  
  23.     if dst_file_path:
  24.         with open(dst_file_path, 'w', encoding='utf-8') as f:
  25.             f.write(pretty_xml_str)
  26.         print(f'formatted xml saved to {dst_file_path}')
  27.     else:
  28.         print(pretty_xml_str)
  29.  
  30.  
  31. def license():
  32.     """Copyleft (c) 2023 k98kurz
  33.  
  34.        Permission to use, copy, modify, and/or distribute this software
  35.        for any purpose with or without fee is hereby granted, provided
  36.        that the above copyleft notice and this permission notice appear in
  37.        all copies.
  38.  
  39.        THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
  40.        WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
  41.        WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
  42.        AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
  43.        CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  44.        OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  45.        NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  46.        CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  47.    """
  48.     return license.__doc__
  49.  
  50.  
  51. if __name__ == '__main__':
  52.     if len(argv) < 2:
  53.         usage(argv[0])
  54.         exit()
  55.     main(*argv[1:])
  56.  
Tags: xml prettifier
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement