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

布莱恩·格雷斯

我在编辑特定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)
鲍里斯·索科洛夫(Boris Sokolov)

请使用文本属性。

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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章