【问题标题】:In Python using etree how do I retain the doc type and declaration在 Python 中使用 etree 如何保留文档类型和声明
【发布时间】:2019-05-01 10:19:19
【问题描述】:

我有一个每天要添加的 xml 文件。问题是当我读入文件然后保存时,它会丢失文件顶部的 xml 声明。我正在使用的代码:

def parseXML():

    xmlFile = open(myfile,'r')
    parser = etree.XMLParser(strip_cdata=False)
    tree = etree.parse(xmlFile, parser)
    return tree

xml_curr = parseXML()
xml_root = xml_curr.getroot()

然后我附加到这个:

xml_root.append(new_elements)

抱歉,如果这不太有意义,python 对我来说是新的。

【问题讨论】:

标签: python xml elementtree


【解决方案1】:
etree.tostring(tree, pretty_print = True, xml_declaration = True, encoding='UTF-8', standalone="yes")

【讨论】:

  • 谢谢,但我想如果我将其转换为字符串,我将无法附加到它。我需要在文件中添加新元素,我这样做是使用:etree.Subelement(...) 然后 xml_root.append(...)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-28
  • 1970-01-01
  • 2015-08-10
  • 1970-01-01
  • 1970-01-01
  • 2011-05-18
  • 2019-12-09
相关资源
最近更新 更多