【问题标题】:How to add an element to xml file by using elementtree如何使用 elementtree 将元素添加到 xml 文件
【发布时间】:2013-01-04 14:38:40
【问题描述】:

我有一个 xml 文件,我正在尝试向其中添加其他元素。 xml 具有下一个结构:

<root>
  <OldNode/>
</root>

我正在寻找的是:

<root>
  <OldNode/>
  <NewNode/>
</root>

但实际上我正在获取下一个 xml:

<root>
  <OldNode/>
</root>

<root>
  <OldNode/>
  <NewNode/>
</root>

我的代码是这样的:

file = open("/tmp/" + executionID +".xml", 'a')
xmlRoot = xml.parse("/tmp/" + executionID +".xml").getroot()

child = xml.Element("NewNode")
xmlRoot.append(child)

xml.ElementTree(root).write(file)

file.close()

谢谢。

【问题讨论】:

    标签: python xml elementtree


    【解决方案1】:

    您打开了要追加的文件,这会将数据添加到末尾。改为使用w 模式打开文件进行写入。更好的是,只需在 ElementTree 对象上使用 .write() 方法:

    tree = xml.parse("/tmp/" + executionID +".xml")
    
    xmlRoot = tree.getroot()
    child = xml.Element("NewNode")
    xmlRoot.append(child)
    
    tree.write("/tmp/" + executionID +".xml")
    

    使用.write() 方法还有一个额外的好处,即您可以设置编码、在需要时强制编写 XML 序言等。

    如果您必须使用打开的文件来美化 XML,请使用 'w' 模式,'a' 打开一个文件进行追加,从而导致您观察到的行为:

    with open("/tmp/" + executionID +".xml", 'w') as output:
         output.write(prettify(tree))
    

    prettify 类似于:

    from xml.etree import ElementTree
    from xml.dom import minidom
    
    def prettify(elem):
        """Return a pretty-printed XML string for the Element.
        """
        rough_string = ElementTree.tostring(elem, 'utf-8')
        reparsed = minidom.parseString(rough_string)
        return reparsed.toprettyxml(indent="  ")
    

    例如minidom 美化技巧。

    【讨论】:

      猜你喜欢
      • 2016-01-20
      • 1970-01-01
      • 1970-01-01
      • 2014-09-12
      • 1970-01-01
      • 2020-08-02
      • 1970-01-01
      • 2013-12-21
      • 1970-01-01
      相关资源
      最近更新 更多