我有一个如下所示的 xml 文件:
<keyboard>
</keyboard>
我想让它看起来像这样:
<keyboard>
<keybind key="W-c-a"><action name="Execute"><command>sudo shutdown now</command></action></keybind>
</keyboard>
我有一个函数来添加它,它有参数可以改变键和命令。这是可能的吗?如果是,我该怎么做?
(函数):
def add_keybinding(self, keys, whatToExec):
keybinding = "<keybind key=\"%s\"><action name=\"Execute\"><command>%s</command><action></keybind>" % (keys, whatToExec)
f = open("/etc/xdg/openbox/rc.xml", "a")
try:
# I want to append the keybinding variable to the <keyboard>
except IOError as e:
print(e)
答案 0 :(得分:0)
从 doc,您可以尝试以下操作:
const [inputTodo, setInputTodo] = useState("")
const [todoList, setTodoList] = useState([])
function handleSubmit(){
console.log(`input Todo: ${inputTodo}`)
setTodoList(inputTodo)
setInputTodo("")
console.log(`Todo List Array: ${todoList}`
}
return(
<div className="addTodo__container">
<div className="add-Todo__inputWrapper">
<input
className="add-Todo__input"
name="todo"
type="text"
placeholder="ADD TODO"
value={inputTodo}
onChange={(e) => setInputTodo([e.target.value])}
/>
</div>
<div className="add-Todo__taskButtonContainer">
<button className="add-Todo__taskBtn" onClick={handleSubmit}>New Task</button>
</div>
</div>
说明:
xml.etree.ElementTree.Element
创建 def add_keybinding(keys, whatToExec, filename):
keybind = ET.Element('keybind')
keybind.set("key", keys)
action = ET.SubElement(keybind, 'action')
action.set("name", "Execute")
command = ET.SubElement(action, 'command')
command.text = whatToExec
tree = ET.parse(filename)
tree.getroot().append(keybind)
tree.write(filename)
标签:keybind
set
设置属性:keybind = ET.Element('keybind')
keybind.set("key", keys)
标记作为 action
的子元素
xml.etree.ElementTree.SubElement
:keybind
action = ET.SubElement(keybind, 'action')
action.set("name", "Execute")
.text
设置 action.set("name", "Execute")
标签内容:command
xml.etree.ElementTree.parse
读取文件:command.text = whatToExec
append
*tree = ET.parse(filename)
标记附加到文档根元素
write
完整示例:
keybind
输出:
import xml.etree.ElementTree as ET
from xml.dom import minidom
def add_keybinding(keys, whatToExec, filename):
keybind = ET.Element('keybind')
keybind.set("key", keys)
action = ET.SubElement(keybind, 'action')
action.set("name", "Execute")
command = ET.SubElement(action, 'command')
command.text = whatToExec
tree = ET.parse(filename)
tree.getroot().append(keybind)
tree.write(filename)
return tree
def prettify(elem):
rough_string = ET.tostring(elem, 'utf-8')
return minidom.parseString(rough_string).toprettyxml(indent=" ")
filename = "test.xml"
for i in range(3):
tree = add_keybinding(str(i), "whatToExec " + str(i), filename)
print(prettify(tree.getroot()))