Python 写入 xml 文件

Python writing to an xml file

我正在尝试写入 xml 文件。我更改了代码中的特定元素,并且能够成功打印它。我需要将它写入文件,而不更改文件的结构。
我的代码:

import os
from lxml import etree


directory = '/Users/eeamesX/work/data/expert/EFTlogs/20160725/IT'
XMLParser = etree.XMLParser(remove_blank_text=True)
for f in os.listdir(directory):
    if f.endswith(".xml"):

        xmlfile = directory + '/' + f



        tree = etree.parse(xmlfile, parser=XMLParser)
        root = tree.getroot()

        hardwareRevisionNode = root.find(".//hardwareRevision")



        if hardwareRevisionNode.text == "5":
            print " "
            print "Old Tag: " + hardwareRevisionNode.text

            x = hardwareRevisionNode.text = "DVT2"

            print "New Tag " +  hardwareRevisionNode.text

当我尝试各种打开和关闭文件的方法时,它只是删除了 xml 文件中的所有数据。使用此方法

outfile = open(xmlfile, 'w')
oufile.write(etree.tostring(tree))
outfile.close()

将我的文件的代码结构更改为一长行。

要在输出文件中换行,您似乎需要将 pretty_print=True 传递给您的消毒(writetostring)调用。

旁注;通常,当您使用 python 打开文件时,您会这样打开它们:

with open('filename.ext', 'mode') as myfile:
    myfile.write(mydata)

这样可以降低文件描述符泄漏的风险。 tree.write("filename.xml") 方法看起来是一种很好且简单的方法,可以避免完全处理文件。

如果您想替换现有 XML 文件中的值,请使用:

tree.write(xmlfile) 

目前您只是完全覆盖您的文件并使用不正确的方法 (open())。 tree.write() 通常是您想要使用的。它可能看起来像这样:

tree = etree.parse(xmlfile, parser=XMLParser)
root = tree.getroot()
hardwareRevisionNode = root.find(".//hardwareRevision")
if hardwareRevisionNode.text == "5":
    print "Old Tag: " + hardwareRevisionNode.text
    hardwareRevisionNode.text = "DVT2"
    print "New Tag: " +  hardwareRevisionNode.text
    tree.write(xmlfile)

https://docs.python.org/2/library/xml.etree.elementtree.html