XML文档只能包含一个根元素。
XML文档的根元素是包含所有被视为文档本身内容的单个元素
例如:
首先创建一个XML文档,以.XML结尾
![](https://i-blog.csdnimg.cn/blog_migrate/424748f78cce91531355a3f6ac78562f.png)
通过python实现对xml的读取:
#新建一个xml对象
demo=text.documentElement
#getElementByTagName()获取节点
usernode=demo.getElementsByTagName('student')
#因为这里有两个student,因此要用for循环
for node in usernode:
#getAttribute()获取属性值 节点的属性值
number=node.getAttribute('num')
#node.getElementsByTagName('name')获取name中的节点
# def getElementsByTagName(self, name):
# return _get_elements_by_tagName_helper(self, name, NodeList())
stu=node.getElementsByTagName('name')
stu1= node.getElementsByTagName('age')
stu2 = node.getElementsByTagName('sex')
#每次取到一个节点都是nodelist的形象,
里面只有一个,因此取第0个才能获取到它真正的节点
stuname=stu[0].childNodes[0].nodeValue
stuage = stu1[0].childNodes[0].nodeValue
stusex = stu2[0].childNodes[0].nodeValue
print("Student:"+"name:"+stuname+"|"+"age:"+stuage+"|"+"sex:"+stusex)
if __name__=='__main__':
getxmldata()
结果如图:
![](https://i-blog.csdnimg.cn/blog_migrate/981f2142c422722b3ca3d851308b948e.png)
通过python实现对xml的写入:
#对xml文件进行添加操作
from xml.etree import cElementTree as ET
tree=ET.parse('user1.xml')
root=tree.getroot()
#对xml文件进行新增操作
#通过根来制作一个子节点
#child=root.getElement('demo',{"id":111})
child=ET.Element('PP',{"demo":"demo"})
#然后将子节点放入根节点中
root.append(child)
#tree.write()将之前的结果写入到根节点中
tree.write("user1.xml")
#对xml文件进行修改操作
#第一步:找到子节点
print(root.findall("test"))
#查看类型,发现是列表,因此要通过for 循环
test=root.findall("test")
for i in test:
root.remove(i)
tree.write("user1.xml")
#对xml文件进行修改操作
test1=root.findall("PP")
#将PP修改成test
for i in test1:
i.set("demo","xxx")
tree.write("user1.xml")
修改结果存储在user1.xml中
![](https://i-blog.csdnimg.cn/blog_migrate/d0a54424d480a1c5d799b96bf4de07e0.png)