用python编写XML行

2024-06-07 15:25:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我的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>

现在,如果我想添加另一行并在第二行(第1列)中添加如下元素:

   <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>

我该怎么办?你知道吗


Tags: 文件textin元素forifdefcell
1条回答
网友
1楼 · 发布于 2024-06-07 15:25:31

将一个字符串视为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)

相关问题 更多 >

    热门问题