[英]How to replace text between two tags of xml using python?
以下是示例xml文件。
<?xml version='1.0' encoding='UTF-8'?>
<a>
<b>
<c>
<d>TEXT</d>
</c>
</b>
</a>
我需要用字符串列表替換“ TEXT”,以便我的xml如下所示。
<?xml version='1.0' encoding='UTF-8'?>
<a>
<b>
<c>
<d>TEXT1,TEXT2,TEXT3</d>
</c>
</b>
</a>
請告訴我如何使用python實現此目的。
嘗試這個:
a = a.replace(<old string>, <new string>)
讀取文件並執行此操作。
這應該工作,
from xml.dom import minidom
doc = minidom.parse('my_xml.xml')
item = doc.getElementsByTagName('d')
print item[0].firstChild.nodeValue
item[0].firstChild.replaceWholeText('TEXT, TEXT1 , etc...')
for s in item: #if you want to loop try this
s.firstChild.replaceWholeText('TEXT, TEXT1 , etc...')
您可以使用lxml
但這取決於您的實際使用目的,下面是一個示例:
from lxml import etree
a = '''<?xml version='1.0' encoding='UTF-8'?>
<a>
<b>
<c>
<d>TEXT</d>
</c>
</b>
</a>'''
tree = etree.fromstring(a)
#for file you need to use tree = etree.parse(filename)
for item in tree:
for data in item:
for point in data:
if point.tag == 'd':
if point.text == 'TEXT':
point.text = 'TEXT,TEXT,TEXT'
print(etree.tostring(tree))
#<a>
# <b>
# <c>
# <d>TEXT,TEXT,TEXT</d>
# </c>
# </b>
#</a>
您可以將xml文件視為文本文件,並使用處理字符串的功能。 例如:
with open('testxml.xml','r') as f:
contents=f.read() #open xml file
stringlist=['Text1','Text2','Text3'] #list of strings you want to replace with
opentag='<d>' #tag in which you want to replace text
closetag='</d>'
oldtext=contents[contents.find(opentag)+3:contents.find(closetag)]
newtext=''.join(str_+',' for str_ in stringlist)[:-1] #ignore last comma
contents=contents.replace(oldtext,newtext) #replace old text with new
with open('testxml.xml','w') as f:
f.write(contents) #write contents to file
在許多情況下,您會有很多嵌套標簽,而這個簡單的腳本將無法工作。 如果您想執行更多高級任務,則可以使用Python的內置XML編輯包ElementTree 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.