Python ElementTree 在解析后不会更新新文件



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

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

当您获得属性i并将其分配给port_id时,您只是有一个常规的Python字符串。在它上面调用replace只是Python字符串.replace()方法。

您希望使用树节点的.set()方法:

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

相关内容

最新更新