- xml_json_yaml_convert
- История выпусков Уведомления о выпусках | Лента RSS
- Загрузка файлов
- Source Distribution
- Built Distribution
- Хеши для xml_json_yaml_convert-1.0.3.tar.gz
- Хеши для xml_json_yaml_convert-1.0.3-py2.py3-none-any.whl
- Помощь
- О PyPI
- Внесение вклада в PyPI
- Использование PyPI
- Saved searches
- Use saved searches to filter your results more quickly
- License
- tarsil/yaml_to_xml
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Convert YAML to XML in Python
- What is the YAML File Format?
- What is XML File Format?
- Convert YAML String to XML String in Python
- Convert YAML String to XML File in Python
- Convert YAML File to an XML String
- Convert YAML File to XML File in Python
- Conclusion
xml_json_yaml_convert
История выпусков Уведомления о выпусках | Лента RSS
Загрузка файлов
Загрузите файл для вашей платформы. Если вы не уверены, какой выбрать, узнайте больше об установке пакетов.
Source Distribution
Uploaded 31 авг. 2021 г. source
Built Distribution
Uploaded 31 авг. 2021 г. py2 py3
Хеши для xml_json_yaml_convert-1.0.3.tar.gz
Алгоритм | Хеш-дайджест | |
---|---|---|
SHA256 | 47a25155314d5a7d8d641ed0582896b700f0a0d7aa45d975b9a99d8e7cb2059a | Копировать |
MD5 | 452b5df21f931b1e62faf19de916b52d | Копировать |
BLAKE2b-256 | e2ab234f93888783f9d48d74e361f4639c2a1fccfaf6c753d2391f57915ccf3f | Копировать |
Хеши для xml_json_yaml_convert-1.0.3-py2.py3-none-any.whl
Алгоритм | Хеш-дайджест | |
---|---|---|
SHA256 | 97f4bf50c88a471d67e5935cbbd4ca7c283225188b5c3b1eb7948a446182a6e3 | Копировать |
MD5 | 6f33a157835d4039c19e5efb6aeda5dd | Копировать |
BLAKE2b-256 | 90899951fd761c90b32be8863e507832bf12de6767db4db5b22a70bc07c7cec6 | Копировать |
Помощь
О PyPI
Внесение вклада в PyPI
Использование PyPI
Разработано и поддерживается сообществом Python’а для сообщества Python’а.
Пожертвуйте сегодня!
PyPI», «Python Package Index» и логотипы блоков являются зарегистрированными товарными знаками Python Software Foundation.
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Converts YAML files to XML using Python 3
License
tarsil/yaml_to_xml
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Script converter of YAML to XML. Written in Python 3
sample: file list: example 1 example 2 items: - name: example1 price: 2 - name: example2 price: 3
list>example 1 example 2 list> sample>filesample> items> price>2price> name>example1name> items> items> price>3price> name>example2name> items>
- This is a simple script that parses an YAML file to XML
- This is testing and sampling purposes but can be changed to production ready
- This should be run in an isolated python environment (virtual env)
This can be executed inside any python environment 3.6+ but I would recommend creating a virtual environment for this purpose and not to break any system
For the user of virtualenv wrapper (my preference), please follow the instructions below:
- In the command line execute pip install virtualenvwrapper-win and linux users pip install virtualenvwrapper
- Create your virtual env mkvirtualenv _name_at_your_choice
- Install the requirements inside pip install -r requirements.txt
- Execute the application python ./app.py with the required parameters
- -l — Location of the file to be parsed (required)
- -d — Destination of the file with the file name after parsing (optional)
- -t — Whether elements get a data type attribute (defaulting to True. E.g.: )
- -s — Whether the output should be on the screen (defaulting to False)
You can run the result only on the screen or just destination or both
- Outputting to a file only python ./app.py -l resources/test.yml -d resources/result.xml -t false -s false
- Outputting to a file and screen python ./app.py -l resources/test.yml -d resources/result.xml -t false
- Outputting only to screen python ./app.py -l resources/test.yml -t false
About
Converts YAML files to XML using Python 3
Convert YAML to XML in Python
YAML and XML files are used extensively to store and transmit data in the software domain. This article discusses how to convert a YAML file or string to XML in Python.
What is the YAML File Format?
YAML is an acronym for “YAML Ain’t Markup Language”. It is a human-readable data serialization format. YAML file format is often used for configuration files, data exchange between languages, and other applications where human readability is important.
A YAML file consists of data represented as key-value pairs, lists, and nested structures. Here’s an example of a simple YAML file.
employee: name: John Doe age: 35 job: title: Software Engineer department: IT years_of_experience: 10 address: street: 123 Main St. city: San Francisco state: CA zip: 94102
This YAML file represents an employee data record with the following attributes.
- name : The name of the employee is «John Doe» .
- age : The employee is 35 years old.
- job : The «job» attribute contains the employee’s job details. For this, it uses the following nested attributes.
- title : The employee’s job title is “Software Engineer”.
- department : The employee’s department is “IT”.
- years_of_experience : The employee has 10 years of experience in their job.
- street : The employee’s street address is “123 Main St.”.
- city : The employee’s city is “San Francisco”.
- state : The employee’s state is “CA”.
- zip : The employee’s zip code is “94102”.
One of the benefits of using the YAML file format is its simplicity and readability. It uses whitespace and indentation to define its structure, which makes it easier for humans to read and edit. Additionally, YAML is supported by a wide range of programming languages. This makes it an ideal format for data exchange between different systems.
What is XML File Format?
XML stands for “Extensible Markup Language” and it is a markup language used for structuring and storing data in a hierarchical format. XML files are plain text files with tags used to define data elements and their attributes, similar to HTML.
XML is often used in web development and data exchange between different applications or systems. An XML document consists of a set of elements, which can have attributes and child elements. The root element is the top-level element that contains all other elements in the document.
If we convert the YAML data shown in the previous example, it looks as follows.
John Doe 35 IT 10 123 Main St. San Francisco CA 94102 Convert YAML String to XML String in Python
To convert a YAML string to XML, we will use the xmltodict module and the yaml module.
The yaml module provides us with the load() method that we can use to convert the yaml string to a python dictionary. The load() method takes the yaml string as its first input argument and the type of yaml loader as the input to the Loader argument. After execution, it returns a python dictionary.
Once we get the python dictionary, we can convert it to an XML string using the unparse() method defined in the xmltodict module. The unparse() method takes the python dictionary as its input argument. After execution, it returns the corresponding XML string.
You can observe this in the following example.
import yaml from yaml import SafeLoader import xmltodict yaml_string="""employee: name: John Doe age: 35 job: title: Software Engineer department: IT years_of_experience: 10 address: street: 123 Main St. city: San Francisco state: CA zip: 94102""" print("The YAML string is:") print(yaml_string) python_dict=yaml.load(yaml_string,Loader=SafeLoader) xml_string=xmltodict.unparse(python_dict) print("The XML string is:") print(xml_string)
The YAML string is: employee: name: John Doe age: 35 job: title: Software Engineer department: IT years_of_experience: 10 address: street: 123 Main St. city: San Francisco state: CA zip: 94102 The XML string is:
John Doe 35 IT 10 123 Main St. San Francisco CA 94102 Convert YAML String to XML File in Python
To convert a YAMl string to an XML file, we will use the following steps.
- First, we will convert the yaml string to a python dictionary using the load() method defined in the yaml module.
- Next, we will open an XML file in write mode using the open() function. The open() function takes the filename as its first input argument and the python literal “w” as its second input argument. After execution, it returns the file pointer.
- Now, we will use the unparse() method defined in the xmltodict module to save the python dictionary as XML in the file. The unparse() method takes the dictionary as its first input argument and the file pointer as the input argument to the output parameter. After execution, it writes the XML content to the file.
- Finally, we will close the XML file using the close() method.
After executing the above steps, we can convert the yaml string to an XML file as shown below.
import yaml from yaml import SafeLoader import xmltodict yaml_string="""employee: name: John Doe age: 35 job: title: Software Engineer department: IT years_of_experience: 10 address: street: 123 Main St. city: San Francisco state: CA zip: 94102""" print("The YAML string is:") print(yaml_string) python_dict=yaml.load(yaml_string,Loader=SafeLoader) file=open("person.xml","w") xml_string=xmltodict.unparse(python_dict,output=file) file.close() print("XML File saved.")
The YAML string is: employee: name: John Doe age: 35 job: title: Software Engineer department: IT years_of_experience: 10 address: street: 123 Main St. city: San Francisco state: CA zip: 94102 XML File saved.
The output file looks as follows.
Convert YAML File to an XML String
Instead of a YAML string, we can also convert a yaml file to an XML string or file. For this, we will use the following YAML file.
To convert a YAML file to an XML string, we will use the following steps.
- First, we will open the yaml file in read mode using the open() method. The open() function takes the file name as its first input argument and the literal “r” as its second input argument. After execution, it returns a file pointer.
- Next, we will create a python dictionary from the yaml file. For this, we will use the load() method defined in the yaml module. The load() method takes the file pointer as its first input argument and the loader type as input to its Loader parameter. After execution, it returns the dictionary created from the yaml file.
- Once we get the dictionary, we will convert it to an XML string using the unparse() method. The unparse() method takes the dictionary as its input argument. After execution, it returns an XML string.
By executing the above steps, we can obtain an XML string from a yaml file. You can observe this in the following example.
import yaml from yaml import SafeLoader import xmltodict yaml_file=open("person.yaml","r") python_dict=yaml.load(yaml_file,Loader=SafeLoader) xml_string=xmltodict.unparse(python_dict) print("The XML string is:") print(xml_string) yaml_file.close()
The XML string is:
John Doe 35 IT 10 123 Main St. San Francisco CA 94102 Convert YAML File to XML File in Python
To convert a YAML file to an XML file, we will first obtain a python dictionary from the yaml file using the load() method as discussed in the previous section.
After obtaining the python dictionary, we will open an XML file in write mode using the open() function. The open() function takes the filename as its first input argument and “w” as its second input argument. After execution, it returns the file pointer.
Once we get the file pointer, we will use the unparse() method defined in the xmltodict module to save the python dictionary as XML in the file. Finally, we will close the file using the close() method.
You can observe the entire process in the following example.
import yaml from yaml import SafeLoader import xmltodict yaml_file=open("person.yaml","r") python_dict=yaml.load(yaml_file,Loader=SafeLoader) file=open("person.xml","w") xml_string=xmltodict.unparse(python_dict,output=file) file.close() yaml_file.close()
Conclusion
In this article, we have discussed different ways to convert a YAML file or String to XML in Python.
To learn more about python programming, you can read this article on how to convert a dictionary to YAML in Python. You might also like this article on custom json encoders in python.
I hope you enjoyed reading this article. Stay tuned for more informative articles.