2013-04-23 63 views
0

我的XML文件是這樣的編寫XML行

<S_Row> 
    <S_Cell><S_CellBody></S_CellBody></S_Cell> 
    <S_Cell><S_CellBody></S_CellBody></S_Cell> 
    <S_Cell><S_CellBody></S_CellBody></S_Cell> 
</S_Row> 

我處理它在Python這樣的:

for i, S_Cell in enumerate(S_Row.findall('S_Cell')): 
     for S_CellBody in S_Cell.getchildren(): 
      if i==0: 
       S_CellBody.text="ABC" 

這給了我輸出像這樣的xml文件:

<S_Row> 
    <S_Cell><S_CellBody>ABC</S_CellBody></S_Cell> 
    <S_Cell><S_CellBody></S_CellBody></S_Cell> 
    <S_Cell><S_CellBody></S_CellBody></S_Cell> 
    </S_Row> 

現在,如果我想添加另一行並添加第二行(第一列)中的元素,如下所示:

<S_Row> 
    <S_Cell><S_CellBody>ABC</S_CellBody></S_Cell> 
    <S_Cell><S_CellBody></S_CellBody></S_Cell> 
    <S_Cell><S_CellBody></S_CellBody></S_Cell> 
    </S_Row> 

    <S_Row> 
    <S_Cell><S_CellBody>DEF</S_CellBody></S_Cell> 
    <S_Cell><S_CellBody></S_CellBody></S_Cell> 
    <S_Cell><S_CellBody></S_CellBody></S_Cell> 
    </S_Row> 

我該怎麼辦?

+0

爲什麼不使用'S_Row.find( './ S_Cell/S_CellBody')。文字= 「ABC」'?在S_Row元素中找到第一個'S_CellBody',這裏不需要使用'enumerate()'。 – 2013-04-23 07:50:30

+0

這是另外不清楚你想如何添加額外的行。它應該是上一行的副本嗎?它應該始終具有相同的3格結構嗎? – 2013-04-23 07:51:10

+0

因爲我在其他行中寫入的元素越多,所以想要保留行的記錄,所以我首先修改完整文件然後寫入,這樣就不會保存已寫入的內容。 – hulk007 2013-04-23 07:53:07

回答

0

考慮作爲了XmlString

import cElementTree  
a1=cElementTree.fromstring(a) 
strlst=['ABC','DEF','GHI'] 
for i,row in enumerate(a1.findall('S_Row')):  
    cb = row.getchildren()[0].getchildren()[0] 
    cb.text = strlst[i+1]   
cElementTree.tostring(a1) 
+0

嗨,我正在使用etree,這會對我有用嗎? – hulk007 2013-04-23 09:11:33

+0

是的,它會爲你啓動 – Kamalakannan 2013-04-23 10:33:08