2017-08-24 230 views
0

下面是示例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實現這一點。

+0

可能的重複[如何在Python中解析XML?](https://stackoverflow.com/questions/1912434/how-do-i-parse-xml-in-python) – JulienD

+0

打開xml文件,讀取行,找到你想要更改的行,更改它,保存它---這是一種方法 - https://stackoverflow.com/a/1591617/7383995 –

回答

0

試試這個:

a = a.replace(<old string>, <new string>) 

讀文件,然後執行此操作。

0

這應該工作,

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...') 
0

您可以使用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> 
0

你可以把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

相關問題