python读取xml,添加节点
采用minidom读取,
在dom上创建新节点,
dom.createElement('item')
再将节点挂在对应节点下
byCardNo.appendChild(item)
将修改后的dom重新写入,建议换一个文件名再测试,避免覆盖
def add(filename):
# 创建dom文档
dom=minidom.parse(filename)
root=dom.documentElement
byCardNo=dom.getElementsByTagName('byCardNo')[0]
item=dom.createElement('item')
item.setAttribute('value','1007')
byCardNo.appendChild(item)
# 将dom对象写入本地xml文件
with open('test.xml', 'w') as f:
dom.writexml(f,indent='\t',addindent='\t',encoding='utf-8')```
示例xml
```bash
<?xml version="1.0" encoding="UTF-8"?>
<ALARM alarminfo="NET_DVR_ACS_ALARM_INFO">
<byCardType value="1" />
<byCardNo value="-" >
<item value ="9990000001"/>
<item value ="9990000002"/>
</byCardNo>
</ALARM>```
![](https://mutouzuo.oss-cn-hangzhou.aliyuncs.com/my/mudouzuo1.png)