2016-08-26 21 views
1

时不会更新新文件,使用ElementTree解析XML中的属性值并编写新的XML文件。它将控制新的更新值并写入一个新文件。但不会更新新文件中的任何更改。请帮我理解我做错了什么。这里是XML & 的Python代码:Python ElementTree在解析

XML

<?xml version="1.0"?> 
<!-- 
--> 
    <req action="get" msg="1" rank="1" rnklst="1" runuf="0" status="1" subtype="list" type="60" univ="IL" version="fhf.12.000.00" lang="ENU" chunklimit="1000" Times="1"> 
     <flds> 
      <f i="bond(long) hff" aggregationtype="WeightedAverage" end="2016-02-29" freq="m" sid="fgg" start="2016-02-29"/> 
      <f i="bond(short) ggg" aggregationtype="WeightedAverage" end="2016-02-29" freq="m" sid="fhf" start="2016-02-29"/> 
     </flds> 
    <dat> 
     <r i="hello" CalculationType="3" Calculate="1" /> 
    </dat> 
</req> 

的Python

import xml.etree.ElementTree as ET 

with open('test.xml', 'rt') as f: 
    tree = ET.parse(f) 

for node in tree.iter('r'): 
    port_id = node.attrib.get('i') 
    new_port_id = port_id.replace(port_id, "new") 
    print node 

tree.write('./new_test.xml') 

回答

1

当你的属性i,它只是分配给port_id,你有一个常规的Python字符串。调用替换它只是Python字符串.replace()方法。

您要使用的etree节点的.set()方法:

for node in tree.iter('r'): 
    node.set('i', "new") 
    print node