Python ElementTree 添加一个孩子

时间:2021-05-10 17:05:07

标签: python xml elementtree

我有一个如下所示的 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)

1 个答案:

答案 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>

说明:

  1. 使用 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
  2. 使用 set 设置属性keybind = ET.Element('keybind')
  3. 使用以下方法创建 keybind.set("key", keys) 标记作为 action 的子元素 xml.etree.ElementTree.SubElementkeybind
  4. 在第 2 步中设置属性:action = ET.SubElement(keybind, 'action')
  5. 创建command标签:action.set("name", "Execute")
  6. 使用 .text 设置 action.set("name", "Execute") 标签内容:command
  7. 使用 xml.etree.ElementTree.parse 读取文件:command.text = whatToExec
  8. 使用 append*
  9. tree = ET.parse(filename) 标记附加到文档根元素
  10. 使用 write
  11. 将新的 xml 导出到文件

完整示例

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()))
相关问题