- 1、python 怎麼修改xml文件內容
- 2、python 替換xml中的一行或者兩行
- 3、求大神指教:如何用python讀取xml文件中指定標籤的文檔內容並將其修改?最好寫下詳細代碼,非常感謝哈!
- 4、Python的XML節點替換或字元串替換問題,此為補償貼,只限luotuo512來回答
- 5、Python的XML節點替換或字元串替換問題
類似於:
#!/usr/bin/evn python
#coding:utf-8
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
import sys
try:
tree = ET.parse(“country.xml”) #打開xml文檔
#root = ET.fromstring(country_string) #從字元串傳遞xml
root = tree.getroot() #獲得root節點
except Exception, e:
print “Error:cannot parse file:country.xml.”
sys.exit(1)
print root.tag, “—“, root.attrib
for child in root:
print child.tag, “—“, child.attrib
print “*”*10
print root[0][1].text #通過下標訪問
print root[0].tag, root[0].text
print “*”*10
for country in root.findall(‘country’): #找到root節點下的所有country節點
rank = country.find(‘rank’).text #子節點下節點rank的值
name = country.get(‘name’) #子節點下屬性name的值
print name, rank
#修改xml文件
for country in root.findall(‘country’):
rank = int(country.find(‘rank’).text)
if rank 50:
root.remove(country)
tree.write(‘output.xml’)
給你推薦一篇文章看看吧:
a=’Range 0-229956 /Range’
b=”‘Range 0-(A-1) /Range’\n’Range B-229956 /Range'”
d=open(“a.xml”,”w”)
while 1:
line=d.readline()
if line==a:
replace(a,b)
ifnotline:
break
##如果你的A,B兩個值是從終端讀取的話在開始read一下就行:
read A
read B
使用python自帶的ElementTree模塊,給你個例子你就知道了
xml文檔
?xml version=”1.0″ encoding=”utf-8″?
config
id0/id
log_pathE:/Python/log_path
/config
Python 代碼,修改id節的內容
from xml.etree import ElementTree
xml_file=’config.xml’
xml=ElementTree.ElementTree(file=xml_file).getroot()
xml.find(‘id’).text=1
兩種方法:
old=open(“test.xml”)
lines=old.readlines()
a=”a/”
i=1
newlines=[]
for line in lines:
if a in line:
line=line.replace(a,”a”+str(i)+”a”+str(i)+”for a/a”+str(i)+””)
i=i+1
newlines.append(line)
for line in newlines:
print line
new=open(“newtest.xml”,”w”)
new.writelines(newlines)
new.close()
old.close()
結果:
roottext
a1a1for a/a1
a2a2for a/a2
a3a3for a/a3
root
import xml.dom.minidom
oldxmlfile=open(“test.xml”)
oldxml=oldxmlfile.read()
oldxmlfile.close()
doc = xml.dom.minidom.parseString(oldxml)
index=1
for node in doc.getElementsByTagName(“a”):
node.tagName=”a”+str(index)
index=index+1
newxml=doc.toprettyxml()
xmlfile=open(“newxml2.xml”,”w”)
xmlfile.write(newxml);
xmlfile.close()
lz是好人。
fpr=open(“text.txt”)
data=fpr.read()
n=0
for i in range(len(data)):
if data[i]==’/’ and data[i+1]==”:
n+=1
newdata=data[0:i]+str(n)+’a’+str(n)+’fora/a’+str(n)+”
k=i
break
for i in range(k+1,len(data)):
if data[i]==’/’ and data[i+1]==”:
n+=1
newdata=newdata+data[i-2:i]+str(n)+’a’+str(n)+’fora/a’+str(n)+”
newdata+=’root’
fpr.close()
fpw=open(“newtext.txt”,”w+”)
fpw.write(newdata)
fpw.close()
測試數據:roottexta/a/a/root
輸出結果:roottexta1a1fora/a1a2a2fora/a2a3a3fora/a3root
原創文章,作者:E8A1P,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/126143.html