标签:节点 参考 引号 list 鼠标 write attr python字典 form
<?xml version="1.0" encoding="utf-8"?>
<note>
<xsq>
<name>显示器</name>
<date>2018/01/01</date>
</xsq>
<sb>
<name>鼠标</name>
<date>2019/01/01</date>
</sb>
<jp>
<name>键盘</name>
<date>2020/01/01</date>
</jp>
</note>
import xml.dom.minidom
from xml.dom.minidom import parse
#读取文件形成树文件
DOMtree = xml.dom.minidom.parse("./t.xml")
#通过树文件,实例根节点
doc = DOMtree.documentElement
print(list(doc.childNodes))
#遍历根节点的子节点
for i in doc.childNodes:
#便利子节点的子节点
for n in i.childNodes:
if n.nodeName == "name":
print(n.childNodes[0].data)
if n.nodeName == "date":
print(n.childNodes[0].data)
import xml.etree.ElementTree
root = xml.etree.ElementTree.parse("./t.xml")
#利用getiterator访问
nodes = root.getiterator()
for node in nodes:
print("{0}--{1}".format(node.tag, node.text))
print("-" * 30)
#利用find和findall方法访问
jpm = root.find("jp")
print("{0}--{1}".format(jpm.tag, jpm.text))
print("-" * 30)
l = root.findall("jp")
for i in l:
print("{0}--{1}".format(i.tag, i.text))
for n in i.iter():
if n.tag == "name":
f "other" in n.attrib.keys():
print(n.attrib["other"])
import xml.etree.ElementTree as ET
note = ET.Element("note")
name = ET.Element("name", {"a":"A"})
date = ET.Element("date", {"b":"B"})
note.append(name)
note.append(date)
t = ET.ElementTree(note)
t.write('family_tree.xml',
encoding='utf-8',
short_empty_elements=False,
xml_declaration=True)
import xml.etree.ElementTree as ET
note = ET.Element("note")
name = note.makeelement("name", {"a":"A"})
date = note.makeelement("date", {"b":"B"})
note.append(name)
note.append(date)
t = ET.ElementTree(note)
t.write('family_tree.xml',
encoding='utf-8',
short_empty_elements=False,
xml_declaration=True)
import xml.etree.ElementTree as ET
#创建根节点
note = ET.Element("note")
#给根节点添加子元素name
name = ET.SubElement(note, "name")
#添加属性
name.attrib = {"w":"w", "h":"h"}
#添加内容
name.text = "abcd"
#给根节点添加子元素date
date = ET.SubElement(note, "date")
date.text = "qwer"
#创建树文件
t = ET.ElementTree(note)
#用树文件创建xml文件,并写入建好的结构
t.write('family_tree.xml',
encoding='utf-8',
short_empty_elements=False,
xml_declaration=True)
import json
j = {"name":"a", "date":"b"}
#把字典转化成json格式的字符串
js = json.dumps(j)
print(type(js))
print(js)
#把json格式字符串转化成python字典
js = json.loads(js)
print(type(js))
print(js)
import json
j = {"name":"a", "date":"b"}
#把python的字典,以json的格式写入文件
with open("t.json", "w") as t:
json.dump(j, t)
#读取json文件,转化为python的字典形式
with open("t.json", "r") as t:
p = json.load(t)
print(type(p))
print(p)
标签:节点 参考 引号 list 鼠标 write attr python字典 form
原文地址:https://www.cnblogs.com/TK-tank/p/12322986.html