首页 > 解决方案 > 读取、修改和写入xml

问题描述

我正在尝试读取一个 xml 文件,更新一个值,然后写入结果。

有问题的xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE config SYSTEM config.dtd">
<config>

    <module name="this">

        <param name="importLabel" value="naksnadksnkas" />

    </module>


</config>

读取和操作值

tree = et.parse("path/file.xml")

root = tree.getroot()

for child in root:
    for sub in child:
        if sub.tag == "param":
            if sub.attrib['name'] == "importLabel":
                sub.attrib['value'] == "working"

tree.write(open('output.xml', 'wb'))

然而,这返回AttributeError: 'xml.etree.ElementTree.Element' object has no attribute 'write'

我可以成功写入tree文件,但这不会捕获我编辑的更新记录。

标签: xmlpython-3.xelementtree

解决方案


我没有收到错误消息。主要问题是您在这一行中使用==而不是:=

sub.attrib['value'] == "working"

代码可以简化。如果你想要一个特定的元素,只需使用find()

from xml.etree import ElementTree as et

tree = et.parse("path/file.xml")

param = tree.find(".//param")
if param.attrib['name'] == "importLabel":
    param.attrib['value'] = "working"

tree.write('output.xml')

推荐阅读