table of Contents
- Read the XML node and attribute values
- Between XML documents and interchangeable dictionary
- Examples JSON string into the class
- Instance of the class is converted JSON string
- Operating SQLite database
- MySQL database operations
- ORM framework
- XML documents stored in the database MongoDB
01. reading XML node and attribute values
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)
to sum up
Between 02.XML documents with interchangeable dictionary
# 字典转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)
to sum up
03. The JSON string into an instance of the class
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)
to sum up
04. Examples of the class into a JSON string
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)
to sum up