读取,修改和写入xml

时间:2019-09-17 08:53:41

标签: xml python-3.x elementtree

我正在尝试读取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写入文件,但这不能捕获我编辑的更新记录。

2 个答案:

答案 0 :(得分:0)

尝试一下:

import xml.etree.ElementTree as et

tree = et.parse("test.xml")
root = tree.getroot()

for child in root.findall("module/param[@name='importLabel']"):
    child.attrib["a"] = "b"

tree.write("output.xml")

答案 1 :(得分:0)

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

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