k98kurz icon

prettifyxml.py

k98kurz | PRO | 02/21/23 03:01:10 PM UTC | 0 ⭐ | 1251 👁️ | Never ⏰ | [xml, prettifier]
Python |

1.79 KB

|

Source Code

|

0 👍

/

0 👎

from sys import argv
from xml.dom import minidom
 
 
def usage(name: str):
    print(f'usage: python {name} src_file_path [dst_file_path]')
 
 
def prettify_xml(src_file_path: str) -> str:
    """Reads the file and returns prettified xml string."""
    dom = minidom.parse(src_file_path)
    return dom.toprettyxml()
 
 
def main(src_file_path: str, dst_file_path: str = None):
    """Run as stand-alone tool."""
    if src_file_path == dst_file_path:
        print('src_file_path and dst_file_path must differ')
        return
 
    pretty_xml_str = prettify_xml(src_file_path)
 
    if dst_file_path:
        with open(dst_file_path, 'w', encoding='utf-8') as f:
            f.write(pretty_xml_str)
        print(f'formatted xml saved to {dst_file_path}')
    else:
        print(pretty_xml_str)
 
 
def license():
    """Copyleft (c) 2023 k98kurz
 
        Permission to use, copy, modify, and/or distribute this software
        for any purpose with or without fee is hereby granted, provided
        that the above copyleft notice and this permission notice appear in
        all copies.
 
        THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
        WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
        WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
        AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
        CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
        OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
        NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
    """
    return license.__doc__
 
 
if __name__ == '__main__':
    if len(argv) < 2:
        usage(argv[0])
        exit()
    main(*argv[1:])
 

Comments