捕获xml文件的选定部分

时间:2013-04-21 18:51:53

标签: python xml-parsing

我的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 S_Cell in S_Row.findall('S_Cell'):
        for S_CellBody in S_Cell.getchildren():
              S_CellBody.text="ABC"

这在xml文件中给出了这样的输出:

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

如果我想在第1行或第2行或第3行插入ABC怎么办? 我如何跟踪我得到的行,因为S_Cell.getchildren()给了我所有的行。

我想保留记录的轨迹,通过该记录我可以在我选择的行(第1行,第2行或第3行)中插入文本。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

例如:

for i, S_Cell in enumerate(S_Row.findall('S_Cell')):
    for S_CellBody in S_Cell.getchildren():
          S_CellBody.text = str(i)

你也可以在循环中放入一些if语句。

答案 1 :(得分:0)

使用计数器变量:

i = 0
for S_CellBody in S_Cell.getchildren():
    i += 1
    if i == 2:
        S_CellBody.text = "ABC"
相关问题