如何用python替换两个xml标签之间的文本?
问题描述:
下面是示例xml文件。如何用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。
可能的重复[如何在Python中解析XML?](https://stackoverflow.com/questions/1912434/how-do-i-parse-xml-in-python) – JulienD
打开xml文件,读取行,找到你想要更改的行,更改它,保存它---这是一种方法 - https://stackoverflow.com/a/1591617/7383995 –