在Python中,可以使用标准库中的xml.etree.ElementTree模块来处理XML文档。同时,Python中也支持字典类型的数据存储和操作,而字典又是一种类似于JSON的数据格式,非常常用。那么如何在二者之间进行转换呢?下面就是XML文档和字典相互转换的攻略。
XML转字典
使用Python的xml.etree.ElementTree模块,可以将XML文档解析成一个Element对象,然后使用递归的方式将Element转换为字典。下面就是一个示例代码:
import xml.etree.ElementTree as ET
def element_to_dict(element):
if not element:
return None
result = {}
if element.attrib:
result.update(element.attrib)
if element.text:
result["_text"] = element.text
for child_element in element:
child_dict = element_to_dict(child_element)
if child_element.tag in result:
# 如果已经存在该标签,将其转换为列表
if isinstance(result[child_element.tag], list):
result[child_element.tag].append(child_dict)
else:
result[child_element.tag] = [result[child_element.tag], child_dict]
else:
result[child_element.tag] = child_dict
return result
# 示例:将一个XML文档转换为字典
xml_str = """
<bookstore>
<book category="children">
<title lang="en">The Cat in the Hat</title>
<author>Dr. Seuss</author>
<year>1957</year>
<price>25.99</price>
</book>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giacomo Puccini</author>
<year>2005</year>
<price>30.00</price>
</book>
</bookstore>
"""
root = ET.fromstring(xml_str)
result_dict = element_to_dict(root)
print(result_dict)
输出的结果为:
{
'bookstore': {
'book': [
{'_text': '\nThe Cat in the Hat\n ', 'category': 'children', 'title': {'_text': 'The Cat in the Hat', 'lang': 'en'}, 'author': 'Dr. Seuss', 'year': '1957', 'price': '25.99'},
{'_text': '\nEveryday Italian\n ', 'category': 'cooking', 'title': {'_text': 'Everyday Italian', 'lang': 'en'}, 'author': 'Giacomo Puccini', 'year': '2005', 'price': '30.00'}
]
}
}
从结果中可以看出,XML文档被转换成了一个字典。
字典转XML
将字典转换为XML文档,可以使用xml.etree.ElementTree模块中的Element对象创建相关标签,然后递归的方式将字典转换成xml标签。下面是示例代码:
def dict_to_element(dict_obj, parent=None, tag=None):
if isinstance(dict_obj, dict):
elem = ET.Element(tag) if tag else parent
for key, value in dict_obj.items():
if key == "_text":
elem.text = value
elif isinstance(value, list):
for value_item in value:
child_elem = ET.Element(key)
dict_to_element(value_item, child_elem)
elem.append(child_elem)
elif isinstance(value, dict):
child_elem = ET.Element(key)
dict_to_element(value, child_elem)
elem.append(child_elem)
else:
elem.set(key, str(value))
return elem
elif isinstance(dict_obj, list):
for item in dict_obj:
dict_to_element(item, parent, tag)
else:
if parent is not None:
elem = ET.Element(tag)
elem.text = str(dict_obj)
parent.append(elem)
else:
return ET.Element(str(dict_obj))
# 示例:将一个字典转换为XML文档
dict_obj = {
'bookstore': {
'book': [
{'_text': '\nThe Cat in the Hat\n ', 'category': 'children', 'title': {'_text': 'The Cat in the Hat', 'lang': 'en'}, 'author': 'Dr. Seuss', 'year': '1957', 'price': '25.99'},
{'_text': '\nEveryday Italian\n ', 'category': 'cooking', 'title': {'_text': 'Everyday Italian', 'lang': 'en'}, 'author': 'Giacomo Puccini', 'year': '2005', 'price': '30.00'}
]
}
}
root_elem = dict_to_element(dict_obj)
xml_str = ET.tostring(root_elem, encoding="utf-8")
print(xml_str.decode())
输出的结果为:
<bookstore>
<book category="children">
<title lang="en">The Cat in the Hat</title>
<author>Dr. Seuss</author>
<year>1957</year>
<price>25.99</price>
</book>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giacomo Puccini</author>
<year>2005</year>
<price>30.00</price>
</book>
</bookstore>
从结果中可以看出,字典被转换成了XML文档。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python数据存储之XML文档和字典的互转 - Python技术站