目录
- 读取XML节点和属性值
- XML文档与字典之间的互相转换
- 将JSON字符串转换为类的实例
- 将类的实例转换为JSON字符串
- 操作SQLite数据库
- 操作MySQL数据库
- ORM框架
- 将XML文档保存在MongoDB数据库
01.读取XML节点和属性值
form xml.etree.ElementTree import parse
doc = parse('file/products.xml')
print(type(doc))
for item in doc.iterfimd('products/product'): # 找product节点
id = item.findtext('id') # 找id节点里的文本
name = item.findtext('name')
price = item.findtext('price')
uuid = item.get('uuid') # 获得uuid属性值
print('uuid','=', uuid)
print('id', '=', id)
print('name', '=', name)
print('price', '=', price)
print('-' * 9)
总结
02.XML文档与字典之间的互相转换
# 字典转xml
import dicttoxml
import os
from xml.dom.minidom import parseString
d = [20, 'name', {'name': 'Bill', 'age': 30, 'salary': 2000},
{'name': 'Mike', 'age': 40, 'salary': 3000},
{'name': 'John', 'age': 20, 'salary': 4000}]
bxml = dicttoxml.dicttoxml(d, custom_root='person')
xml = bxml.decode('utf-8')
dom = parseString(xml)
prettyxml = dom.toprettyxml(indent=' ')
f = open('persons.xml', 'w', encoding='utf-8')
f.write(prettyxml)
f.close()
# xml转字典
import xmltodict
import pprint
f = open('persons.xml', 'r', encoding='utf-8')
xml = f.read()
d = xmltodict.parse(xml)
pp = pprint.PrettyPrinter(indent=2)
pp.pprint(d)
print(d)
总结
03.将JSON字符串转换为类的实例
import json
class Product:
def __init__(self, d):
self.__dict__ = d
f = open('products.json', 'r')
jsonStr = f.read()
product = json.loads(jsonStr, object_hook=Product) # 先用loads把type变为 'dict',再引入Product类
print(product.name)
print(product.price)
# 方法二:创建转换函数
def json2Product(d):
return Product(d)
product1 = json.loads(jsonStr, object_hook=json2Product) # json2Product不能加(),否则为调用
print(product1.name)
print(product1.price)
总结
04.将类的实例转换为JSON字符串
import json
class Product:
def __init__(self, name, price, count):
self.name = name
self.price = price
self.count = count
product = Product('特斯拉', 100000, 20)
def product2Dict(obj):
return {
'name':obj.name,
'price':obj.price,
'count':obj.count
}
jsonStr = json.dumps(product, default=product2Dict, ensure_ascii=False)
print(jsonStr)
{"name": "特斯拉", "price": 100000, "count": 20}
jsonStr = json.dumps(product, default=product2Dict, ensure_ascii=True) # 若改为True,则中文不会按原来输出
{"name": "\u7279\u65af\u62c9", "price": 100000, "count": 20}
# 问题二
f = open('products.json', 'r', encoding='utf-8')
jsonStr = f.read()
class Product:
def __init__(self, d):
self.__dict__ = d
products = json.loads(jsonStr, object_hook=Product)
for product in products:
print(product.name)
jsonStr = json.dumps(products, default=product2Dict, ensure_ascii=False))
print(jsonStr)
总结