【问题标题】:Python ElementTree won't update new file after parsingPython ElementTree 解析后不会更新新文件
【发布时间】:2016-08-26 16:23:31
【问题描述】:

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

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

【问题讨论】:

    标签: python xml xml-parsing elementtree


    【解决方案1】:

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

    你想使用etree节点的.set()方法:

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

    【讨论】:

      猜你喜欢
      • 2015-08-23
      • 2013-05-23
      • 2019-03-23
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多