当前位置:网站首页>XML json YAML interconversion

XML json YAML interconversion

2022-06-09 07:54:00 Huang Yuanbao

Préface: Une réalisation xml json yamlDes scripts cassés qui tournent entre eux,À volonté

  • xml_json_yaml_converter.py
    """ xml json yaml Outil d'échange C'est vrai. xmltodict Emballage secondaire En fin de compte, ces structures de données passent par python DedictComme données intermédiaires Conversion """
    import _io
    import os
    import json
    import yaml
    import xmltodict
    from copy import deepcopy
    from xml.dom import minidom
    
    
    class Converter:
        
        def __init__(self):
            self.data = None
            self.params = None  # Paramètres initiaux
    
        def dict2xml(self):
    
            if not isinstance(self.data, dict):
                raise TypeError(f'dict2xml expected a dict but received a {
            type(self.data)}')
            if "xml" not in self.data:
                new = dict()
                new["xml"] = deepcopy(self.data)
                self.data = new
    
            return xmltodict.unparse(self.data)
    
        @staticmethod
        def _write_xml_format(string, filename):  # J'ai essayé plusieurs façons SortiexmlTout en ligne,  Donc Formater la sortie comme suit xml
            dom = minidom.parseString(string)
            with open(filename, "w") as f:
                dom.writexml(f, "", "\t", "\n", encoding="utf-8")
                f.flush()
    
        def xml2dict(self):
            if isinstance(self.data, str):
                return xmltodict.parse(self.data)
    
            elif isinstance(self.data, _io.TextIOWrapper):
                return xmltodict.parse(self.data.read())
    
            raise TypeError(f'xml2dict expected a string or _io.TextIOWrapper, but received a {
            self.data}')
    
        def dict2yaml(self):
            if not isinstance(self.data, dict):
                raise TypeError(f'dict2yaml expected a dict but received a {
            type(self.data)}')
    
            return yaml.safe_dump(self.data)
    
        def yaml2dict(self):
            if isinstance(self.data, str):
                return yaml.safe_load(self.data)
    
            elif isinstance(self.data, _io.TextIOWrapper):
                return yaml.safe_load(self.data)
    
            raise TypeError(f'from_yaml expected a string or _io.TextIOWrapper, but received a {
            self.data}')
    
        def dict2json(self):
    
            if not isinstance(self.data, dict):
                raise TypeError(f'to_json expected a dict but received a {
            type(self.data)}')
    
            return json.dumps(self.data, indent=4)
    
        def json2dict(self):
            if isinstance(self.data, str):
                return json.loads(self.data)
    
            elif isinstance(self.data, _io.TextIOWrapper):
                return json.load(self.data)
    
            raise TypeError(f'from_json expected a string or _io.TextIOWrapper, but received a {
            self.data}')
    
        def _fd(self, data):
            """ Renvoie la poignée de fichier   Nom du fichier avec suffixe   Va entrer ici en premier  open Retourner la poignée"""
            return open(data, encoding="utf-8")
    
        # -------------------------------------------- Tout ce qui précède dict Et  Rotation structurelle   Voici les interfaces  ----------------------------------
    
        def pre_converter(self, data):
            self.params = data
    
            if isinstance(data, str):
                endswith = os.path.splitext(data)
                if len(endswith) == 2:  # La transmission est  Une adresse de fichier avec suffixe 
                    self.data = self._fd(data)
                    self.params = endswith[0]  #  Obtenir le préfixe comme préfixe de fichier pour la sortie 
            else:
    
                self.data = data
    
        def hook_converter(self, value, endswith):  #  Opération après conversion   Écrire des fichiers, etc 
    
            if self.params is not None:
                filename = self.params + "." + endswith
                if endswith == "xml":
                    self._write_xml_format(value, filename)
                else:
                    with open(filename, "w") as f:
                        f.write(value)
                        f.flush()
    
        def xml2json(self, data):
            self.pre_converter(data)
            self.data = self.xml2dict()
            value = self.dict2json()
            self.hook_converter(value, "json")
    
        def xml2yaml(self, data):
            self.pre_converter(data)
            self.data = self.xml2dict()
            value = self.dict2yaml()
            self.hook_converter(value, "yaml")
    
        def json2xml(self, data):
            self.pre_converter(data)
            self.data = self.json2dict()
            value = self.dict2xml()
            self.hook_converter(value, "xml")
    
        def json2yaml(self, data):
            self.pre_converter(data)
            self.data = self.json2dict()
            value = self.dict2yaml()
            self.hook_converter(value, "yaml")
    
        def yaml2xml(self, data):
            self.pre_converter(data)
            self.data = self.yaml2dict()
            value = self.dict2xml()
            self.hook_converter(value, "xml")
    
        def yaml2json(self, data):
            self.pre_converter(data)
            self.data = self.yaml2dict()
            value = self.dict2json()
            self.hook_converter(value, "json")
    
    
    if __name__ == '__main__':
        import fire
    
        fire.Fire(Converter)
    
  • Les ordres
    C'est une simple ligne de commande , Faire trop de fonctions , Un peu humble
    • python3 xml_json_yaml_converter.py xml2json xx.xml Générer un jsonDocumentation
    • python3 xml_json_yaml_converter.py json2xml xx.json Générer un xmlDocumentation
    • Pour les autres commandes, voir ci - dessus
原网站

版权声明
本文为[Huang Yuanbao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206090754309896.html