Python的XML节点替换或字符串替换问题,此为补偿贴,只限luotuo512来回答
1个回答
2013-06-18 · 知道合伙人软件行家
关注
展开全部
两种方法:
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()
结果:
<root>text
<a1>a1for a</a1>
<a2>a2for a</a2>
<a3>a3for 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是好人。
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()
结果:
<root>text
<a1>a1for a</a1>
<a2>a2for a</a2>
<a3>a3for 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是好人。
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询