XML 是一个结构化数据格式。
from xml.etree.ElementTree import Element, SubElement, tostring
from xml.dom.minidom import parseString
Articles = {
'0001': {
"title": "Python进阶-GUI-Tk接口",
"name": "小团子",
"time": 2019,
"image": "www.shujuyuntuan.com/static/image/0001.jpg",
},
'0002': {
"title": "Python进阶-Web 服务",
"name": "数据云团",
"time": 2018
},
'0003': {
"title": "Python进阶-GUI-目录树",
"name": "团子",
"time": 2017,
"tags": "python"
},
}
首先创建顶层对象,即 articles,接着将所有其它内容添加到该节点下。对于每一篇文章,都添加一个 article 子节点,如果上面的原字典没有提供封面图和标签,则使用提供的默认值。接着遍历所有键值对,将这些内容作为其它子节点添加到每个 article 中。
articles = Element("articles")
for article_id, info in Articles.items():
article = SubElement(articles, 'article')
info.setdefault("image", "www.shujuyuntuan.com/static/image/default.jpg")
info.setdefault("tags", "python")
for key, val in info.items():
SubElement(article, key).text = ", ".join(str(val).split(":"))
xml = tostring(articles)
print("*** XML 数据 ***")
print(xml)
将数据用其它几种格式转储,遍历所有节点作为一个大的平坦结构;在 XML 文档中进行搜索。
dom = parseString(xml)
print(dom.toprettyxml(" "))
for elmt in articles.getiterator():
print(elmt.tag, '-', elmt.text)
for article in articles.findall('.//title'):
print(article.text)