Python ElementTree 解析后不会更新新文件
Python ElementTree won't update new file after parsing
使用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 string .replace()
方法。
您想使用etree节点的.set()
方法:
for node in tree.iter('r'):
node.set('i', "new")
print node
使用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 string .replace()
方法。
您想使用etree节点的.set()
方法:
for node in tree.iter('r'):
node.set('i', "new")
print node