当前位置:网站首页>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
- python3 xml_json_yaml_converter.py xml2json xx.xml
边栏推荐
- MySQL: merge query results and aliases
- Two ways to achieve single sign on
- 2022 simulation test platform operation of gantry crane driver theory question bank
- Use of Shopify port in EDI system of bridge of knowledge and Practice
- 2022年中式烹调师(初级)考试题库及在线模拟考试
- [school experiment + Blue Bridge Cup topic] water connection problem: there is a water room in the school. There are m taps in the water room for students to turn on water. Each tap has the same water
- What is SQA in cmm/cmmi? What is the relationship between SQA and testing
- 2022广东省安全员C证第三批(专职安全生产管理人员)考题及模拟考试
- Taobao classification encyclopedia and its grouping (mysql, XLS) files, hierarchical relationship, spelling, hierarchy, hierarchical tree, tips, data on February 28, 2022
- 蓝桥杯电子类单片机第十一届决赛试题
猜你喜欢

A group of interesting pictures to explain the status code

Taobao classification encyclopedia and its grouping (mysql, XLS) files, hierarchical relationship, spelling, hierarchy, hierarchical tree, tips, data on February 28, 2022

Selenium: element positioning

Jasperreport generate PDF report section

Google browser F12 (developer tool) ---network

The cumulative net worth of more than 1100 products fell below 0.8. Is the performance of private placement good this year?

IELTS复习1

【6月第一周学习记录】UU-Computer vision(1):3D reconstruction&Camera calibration

实时监控,智能预警,疾控中心的战疫“速度”

How do I add the hours of the current date in SQL Server- How to add hours to current date in SQL Server?
随机推荐
C语言复习7
SQL or NoSQL, you will understand after reading this article
Summarize 2021 Test Engineer Interview Questions (including answers)
2022 simulation test platform operation of gantry crane driver theory question bank
What is SQA in cmm/cmmi? What is the relationship between SQA and testing
2022年全國最新消防設施操作員(中級消防設施操作員)考試模擬題庫及答案
At time_ What happens to TCP connections in wait status after SYN is received?
Apache configuration and application (building web host, log segmentation and awstats analysis system)
Graphic knowledge points: leakcanary
知行之桥EDI系统Shopify端口的使用
PHP date format conversion simplified month day without 0, for example: 22.2.9
【学校实验+蓝桥杯题目】接水问题:学校里有一个水房,水房里一共装有m个龙头可供同学们打开水,每个龙头每秒钟的供水量相等,均为1。现在有n名同学准备接水,他们的初始接水顺序已经确定......
Advanced SQL query
实时监控,智能预警,疾控中心的战疫“速度”
JS get form data
Force to trigger epollin and epollout events
MySQL: merge query results and aliases
Fabric. JS activation input box
CV学习笔记-CNN-VGG
The 11th finals of the electronic single chip microcomputer of the Blue Bridge Cup