我在编辑特定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)
答案 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)