在 Python 中将具有属性的元素添加到 XML

Add element with attribute to XML in Python

我需要我的 XML 文件看起来像:

<house>
  <window>
     <door color="blue">
         <table size="32">
          (other things will be here in the middle)
         </table>
     </door>
  </window>
</house>

我已经有了房子和windows。如何添加门和桌子? 我正在使用 xml.etree.ElementTree 并尝试将它们添加为子元素,如下所示:

root = ET.parse(filename).getroot()
path = root.find('window')
new = ET.SubElement(path, "door", color="blue")

我也试过将它添加为这样的元素:

new = ET.Element("window", dict(color="blue"))
path.append(new)

但这并没有实现我的目标,因为他们需要在最后关闭 (</door>),而我得到的只是 <door color="blue"/>.

因为你的用户名和我的头像匹配 :) 尝试这些更改 - 使用 short_empty_elements() 参数:

new = ET.SubElement(path, "door", color="blue")
print(ET.tostring(root, short_empty_elements=False).decode())

输出:

<house>
  <window>
     <door color="blue">
         <table size="32">
          (other things will be here in the middle)
         </table>
     </door>
  <door color="blue"></door></window>
</house>