使用属性将字典转换为 XML
Converting a dict to XML with attributes
我在 python 中使用 dicttoxml 将 dict 转换为 XML 。
我需要将字典转换为 XML 属性。
例如:
dict
[
{
"@name":"Ravi",
"@age":21,
"college":"Anna University"
}
]
输出XML
<Student name="Ravi" age=21>
<college>Anna University</college>
</Student>
代码
dicttoxml(dict, custom_root='Student', attr_type=False, root=True)
实际输出
<Student>
<key name="name">Ravi</key>
<key name="age">21</key>
<college>Anna University</college>
</Student>
dicttoxml 目前还不支持此功能,尽管该问题已开放很长时间。
https://github.com/quandyfactory/dicttoxml/issues/27
不过如果您的需求不是那么复杂,您可以试试这个简单的序列化程序。
https://gist.github.com/reimund/5435343/
在这里找到它:- Serialize Python dictionary to XML
我可能会建议 declxml(完全披露:我写的)。使用 declxml,您可以创建一个名为 processor 的对象,它以声明方式定义 XML 的结构。您可以使用处理器来解析和序列化 XML 数据。 declxml 用于序列化字典、对象和命名元组。它处理属性和元素数组并执行基本验证。
import declxml as xml
student = {
'name':'Ravi',
'age':21,
'college':'Anna University'
}
student_processor = xml.dictionary('Student', [
xml.string('.', attribute='name'),
xml.integer('.', attribute='age'),
xml.string('college')
])
xml.serialize_to_string(student_processor, student, indent=' ')
产生所需的输出
<?xml version="1.0" ?>
<Student age="21" name="Ravi">
<college>Anna University</college>
</Student>
我有类似的要求将 XML 转换为 dict,反之亦然。我使用了一个名为 xmltodict 的库。这个库允许你从 dict 反转为 xml 属性。
dict
xmldata = { 'student': {
"@name":"Ravi",
"@age":21,
"college":"Anna University"
}}
代码
import xmltodict
print(xmltodict.unparse(xmldata, pretty=True))
我也在使用 xmltodict,我认为 Hisham 的回答中有语法错误,但我无法发表评论,所以在这里:
import xmltodict
xmldata = {
'Student': {
'@name':'Ravi',
'@age':21,
"college":"Anna University"
}
}
print(xmltodict.unparse(xmldata,pretty=True))
输出
<?xml version="1.0" encoding="utf-8"?>
<Student name="Ravi" age="21">
<college>Anna University</college>
</Student>
下面是一些相对简单的代码,可以根据对象类型做出决定。如果一个对象是一个字典,它的键的值在历史上被认为是像 C 或 Java 这样的语言中的“原始”的键被写为属性,否则会创建一个子元素。如果对象是列表,则会为每个列表项创建一个 li
元素。原始项目被写为元素文本,而字典项目被写为属性。
#! python3-64
from lxml import etree
import json
import typing
def json_obj_to_xml(parent_element: typing.Optional[etree.Element], new_element_name: str, obj: typing.Union[bool, float, int, str, dict, list]):
"""
Recursively walk an object and return its XML representation.
Args:
parent_element (typing.Optional[etree.Element]): The element that will be the parent of the element that this
function will create and return.
new_element_name (str): The name of the element that will be created.
obj (typing.Union[bool, float, int, str, dict, list]): The object to return XML for. It is expected that all
objects passed to this function can be represented in JSON.
Returns:
result (etree.Element): An XML element.
"""
if parent_element is not None:
new_element = etree.SubElement(parent_element, new_element_name)
else:
new_element = etree.Element(new_element_name)
if type(obj) == dict:
for key, value in obj.items():
if type(value) in (dict, list):
json_obj_to_xml(new_element, key, value)
else:
# Convert values to a string, make sure boolean values are lowercase
new_element.attrib[key] = str(value).lower() if type(value) == bool else str(value)
elif type(obj) == list:
for list_item in obj:
# List items have to have a name. Here we borrow "li" from HTML which stands for list item.
json_obj_to_xml(new_element, 'li', list_item)
else:
# Convert everything to a string, make sure boolean values are lowercase
new_element.text = str(obj).lower() if type(obj) == bool else str(obj)
return new_element
# Read JSON file into a dictionary
json_file = r'C:\Users\ubiquibacon\Desktop\some_json_file.json'
json_file_hndl = open(json_file)
json_dict = json.load(json_file_hndl)
json_file_hndl.close()
# Recursively walk the dictionary to create the XML
root_xml_element = json_obj_to_xml(None, 'root', json_dict)
# Write the XML file
xml_file = f'{json_file}.xml'
with open(xml_file, 'wb') as xml_file_hndl:
xml_file_hndl.write(etree.tostring(root_xml_element, pretty_print=True, xml_declaration=True))
我在 python 中使用 dicttoxml 将 dict 转换为 XML 。
我需要将字典转换为 XML 属性。
例如:
dict
[
{
"@name":"Ravi",
"@age":21,
"college":"Anna University"
}
]
输出XML
<Student name="Ravi" age=21>
<college>Anna University</college>
</Student>
代码
dicttoxml(dict, custom_root='Student', attr_type=False, root=True)
实际输出
<Student>
<key name="name">Ravi</key>
<key name="age">21</key>
<college>Anna University</college>
</Student>
dicttoxml 目前还不支持此功能,尽管该问题已开放很长时间。 https://github.com/quandyfactory/dicttoxml/issues/27
不过如果您的需求不是那么复杂,您可以试试这个简单的序列化程序。
https://gist.github.com/reimund/5435343/
在这里找到它:- Serialize Python dictionary to XML
我可能会建议 declxml(完全披露:我写的)。使用 declxml,您可以创建一个名为 processor 的对象,它以声明方式定义 XML 的结构。您可以使用处理器来解析和序列化 XML 数据。 declxml 用于序列化字典、对象和命名元组。它处理属性和元素数组并执行基本验证。
import declxml as xml
student = {
'name':'Ravi',
'age':21,
'college':'Anna University'
}
student_processor = xml.dictionary('Student', [
xml.string('.', attribute='name'),
xml.integer('.', attribute='age'),
xml.string('college')
])
xml.serialize_to_string(student_processor, student, indent=' ')
产生所需的输出
<?xml version="1.0" ?>
<Student age="21" name="Ravi">
<college>Anna University</college>
</Student>
我有类似的要求将 XML 转换为 dict,反之亦然。我使用了一个名为 xmltodict 的库。这个库允许你从 dict 反转为 xml 属性。
dict
xmldata = { 'student': {
"@name":"Ravi",
"@age":21,
"college":"Anna University"
}}
代码
import xmltodict
print(xmltodict.unparse(xmldata, pretty=True))
我也在使用 xmltodict,我认为 Hisham 的回答中有语法错误,但我无法发表评论,所以在这里:
import xmltodict
xmldata = {
'Student': {
'@name':'Ravi',
'@age':21,
"college":"Anna University"
}
}
print(xmltodict.unparse(xmldata,pretty=True))
输出
<?xml version="1.0" encoding="utf-8"?>
<Student name="Ravi" age="21">
<college>Anna University</college>
</Student>
下面是一些相对简单的代码,可以根据对象类型做出决定。如果一个对象是一个字典,它的键的值在历史上被认为是像 C 或 Java 这样的语言中的“原始”的键被写为属性,否则会创建一个子元素。如果对象是列表,则会为每个列表项创建一个 li
元素。原始项目被写为元素文本,而字典项目被写为属性。
#! python3-64
from lxml import etree
import json
import typing
def json_obj_to_xml(parent_element: typing.Optional[etree.Element], new_element_name: str, obj: typing.Union[bool, float, int, str, dict, list]):
"""
Recursively walk an object and return its XML representation.
Args:
parent_element (typing.Optional[etree.Element]): The element that will be the parent of the element that this
function will create and return.
new_element_name (str): The name of the element that will be created.
obj (typing.Union[bool, float, int, str, dict, list]): The object to return XML for. It is expected that all
objects passed to this function can be represented in JSON.
Returns:
result (etree.Element): An XML element.
"""
if parent_element is not None:
new_element = etree.SubElement(parent_element, new_element_name)
else:
new_element = etree.Element(new_element_name)
if type(obj) == dict:
for key, value in obj.items():
if type(value) in (dict, list):
json_obj_to_xml(new_element, key, value)
else:
# Convert values to a string, make sure boolean values are lowercase
new_element.attrib[key] = str(value).lower() if type(value) == bool else str(value)
elif type(obj) == list:
for list_item in obj:
# List items have to have a name. Here we borrow "li" from HTML which stands for list item.
json_obj_to_xml(new_element, 'li', list_item)
else:
# Convert everything to a string, make sure boolean values are lowercase
new_element.text = str(obj).lower() if type(obj) == bool else str(obj)
return new_element
# Read JSON file into a dictionary
json_file = r'C:\Users\ubiquibacon\Desktop\some_json_file.json'
json_file_hndl = open(json_file)
json_dict = json.load(json_file_hndl)
json_file_hndl.close()
# Recursively walk the dictionary to create the XML
root_xml_element = json_obj_to_xml(None, 'root', json_dict)
# Write the XML file
xml_file = f'{json_file}.xml'
with open(xml_file, 'wb') as xml_file_hndl:
xml_file_hndl.write(etree.tostring(root_xml_element, pretty_print=True, xml_declaration=True))