使用elementree编辑XML文件中的属性的问题

时间:2018-10-01 17:08:19

标签: python-3.x

我在编辑特定XML文档中的属性时遇到问题。我已经弄清楚了如何使用“ findall”功能提取属性,但是我似乎找不到找到将新属性写入字段的有效方法。有人可以告诉我用于编辑特定XML元素的语法吗?

import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element, SubElement

input = '''
<Configuration>
    <UserInterface>
        <OSD>
            <HalfwakeMessage>Attribute to edit.</HalfwakeMessage>
        </OSD>
    </UserInterface>
</Configuration>'''
stuff=ET.fromstring(input)

lst=stuff.findall('UserInterface/OSD')

for i in lst:
    x=i.find('HalfwakeMessage')
    print(x)

2 个答案:

答案 0 :(得分:1)

请使用文本属性。

import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element, SubElement

input = '''
<Configuration>
    <UserInterface>
        <OSD>
            <HalfwakeMessage>Attribute to edit.</HalfwakeMessage>
        </OSD>
    </UserInterface>
</Configuration>'''

print(input)

stuff = ET.fromstring(input)
print(stuff)

lst=stuff.findall('UserInterface/OSD')

for i in lst:
    x=i.find('HalfwakeMessage')
    print(x.text)
    x.text = 'New text'
    print(x.text)


output = ET.tostring(stuff)
print(output)

答案 1 :(得分:0)

要编辑元素,请使用insertset