import xml.etree.ElementTree as ET
'''
读取xml文件:
引入ET函数
获取元素树对象
获取根节点
获取tag 和attrib
循环访问 所有元素节点 根据索引访问元素节点
'''
tree = ET.ElementTree(file=r'./demo.xml')
root = tree.getroot()
print(root.tag, root.attrib)
for tag in root:
print(tag.tag, tag.attrib)
print(tag[0].text)
for c_tag in tag:
print(c_tag.tag, c_tag.text)
"""
元素对象.find(tag) 返回该标签对应的元素对象
findAll() 返回所有对象
"""
```python
from xml.dom.minidom import Document
doc = Document()
root = doc.createElement("root")
doc.appendChild(root)
head = doc.createElement("head")
root.appendChild(head)
text1 = doc.createTextNode('1')
node = doc.createElement("node")
node.appendChild(text1)
head.appendChild(node)
text2 = doc.createTextNode("访问成功")
msg = doc.createElement("msg")
msg.appendChild(text2)
head.appendChild(msg)
print(doc.toprettyxml(encoding='UTF-8').decode('UTF-8'))
with open("demow.xml", "w+") as f:
f.write(doc.toprettyxml(encoding='UTF-8').decode('UTF-8'))
f.close()