py手册:http://docs.python.org/2/library/xml.etree.elementtree.html
xml内容如下:
<ChannelInfoService>
<channels>
<channel billEndDate="3000-01-01 00:00:00" billIsBill="true" billStartDate="1970-01-01 00:00:00" billingId="38352" billingName="http://redirect.baishitong.ccgslb.com.cn" channelId="53841" channelName="redirect.baishitong.ccgslb.com.cn" channelType="HTTP" endDate="3000-01-01 00:00:00" hasPeerLog="false" internalIp="255.255.255.255" pubAbroadConfigNodeIds="000" pubCompressType="gz" pubConfigNodeIds="000" pubContinueDays="31" pubCustEmail="email@email.com" pubEndDate="3000-01-01 00:00:00" pubFileNameDetail="fileNameDetail" pubFileNameFlag="OLD" pubFormatType="w3c_domain" pubFtpDir="/" pubFtpIp="255.255.255.255" pubFtpPassword="password" pubFtpPort="21" pubFtpUser="user" pubHasHeader="true" pubHeaderStr="#" pubIsFilter="true" pubIsIncremenal="false" pubIsPub="false" pubIsSplit="false" pubLimitTime="23" pubLogDelayHour="4" pubLogHourInterval="24" pubLogIdentifier="cc" pubLogIsSort="true" pubMergeType="ALL" pubMimeFilter="image" pubPriority="P5" pubReceiveSaveDay="12" pubResultSaveDay="31" pubSplitSize="100" pubStartDate="1970-01-01 00:00:00" pubSwitchEndDate="2021-04-12 00:00:00" pubSwitchStartDate="2011-04-12 00:00:00" pubUrlFilter="gif,jpg,jpeg,png,bmp,ico,swf" pubWay="HTTP" recordVersion="2011-12-29 16:59:11" startDate="1970-01-01 00:00:00" statEndDate="3000-01-01 00:00:00" statIsStat="true" statNeedUrlday="false" statNotstolenPattern=".*" statStartDate="1970-01-01 00:00:00" userId="2711" userName="Jane" />
</channels>
</ChannelInfoService>
将userName的值Jane修改为SAM:
#coding:utf-8
import xml.etree.ElementTree as ET
import sys
def main():
# 加载并且解析这个 XML,也可以使用 tree = ET.ElementTree(file='doc1.xml')将整个 XML 解析为一棵树
tree = ET.parse(r"G:\LogPubChannelConfig.xml")
# 获得根结点元素
root=tree.getroot()
#iter 方法可以对子结点进行深度优先遍历
#也可以接受一个标签名字,只遍历指定标签的元素
for elem in tree.iter(tag='channel'):
#修改 元素的值
elem.attrib['userName']="SAM"
#将xml写入原文件
tree.write(r"G:\LogPubChannelConfig.xml")
if __name__ == '__main__':
main()
原文链接:https://www.f2er.com/xml/299049.html