使用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')
答案 0 :(得分:1)
当您获得属性i
并将其分配给port_id
时,您只需要一个常规的Python字符串。调用replace就是Python字符串.replace()
方法。
您想使用etree节点的.set()
方法:
for node in tree.iter('r'):
node.set('i', "new")
print node