【问题标题】:How to write ElementTree data to a file in python如何将ElementTree数据写入python中的文件
【发布时间】:2020-03-30 07:59:23
【问题描述】:

我已经制作了一个这样的示例 XML 文件:

from lxml import etree
import xml.etree.ElementTree as et
root = etree.Element("{" + link + "}linkbase", attrib={"{" + xsi + "}schemaLocation" : schemaLocation}, nsmap=ns)
ch1_lvl1 = etree.SubElement(root, "{" + link + "}referenceLink", attrib={"{" + xlink + "}type" : elem_type[0], "{" + xlink + "}role" : role_prefix + role[0]})
ch1_lvl2 = etree.SubElement(ch1_lvl1, "{" + link + "}loc", attrib={"{" + xlink + "}type" : elem_type[1], "{" + xlink + "}href" : ch1_lvl2_href, "{" + xlink + "}label" : ch1_lvl2_label})
ch2_lvl2 = etree.SubElement(ch1_lvl1, "{" + link + "}reference", attrib={"{" + xlink + "}type" : elem_type[2], "{" + xlink + "}label" : ch2_lvl2_label, "{" + xlink + "}role" : role_prefix + role[1], "{" + xlink + "}id" : ch2_lvl2_id} )
ch1_lvl3 = etree.SubElement(ch2_lvl2, "{" + in_rbi_rep_par + "}Circular").text="DBS.No.FBC.BC.34/13.12.001/99-2000  dt April 6, 2000"
print(etree.tostring(root, pretty_print=True).decode("utf-8"))
r = etree.tostring(root).decode("utf-8")
file = open('s.txt','w')
file.write(r)

我不包括ns, schemaLocation 和其他变量的定义,因为我认为它们与问题的上下文无关。 上面的代码生成一个只有Circular标签数据的文件,即DBS.No.FBC.BC.34/13.12.001/99-2000 dt April 6, 2000。但是,我希望整个 XML 应该像这样生成:

<link:linkbase xmlns:link="http://www.xbrl.org/2003/linkbase" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:in-ghi-rep-par="http://www.ghi.org/in-ghi-rep-par" xmlns:ref="http://www.xbrl.org/2006/ref" xmlns:xbrli="http://www.xbrl.org/2003/instance" xmlns:xlink="http://www.w3.org/1999/xlink" xsi:schemaLocation="http://www.xbrl.org/2006/ref http://www.xbrl.org/2006/ref-2006-02-27.xsd http://www.ghi.org/in-ghi-rep-par &#10;../core/in-ghi-rep-par.xsd http://www.xbrl.org/2003/linkbase http://www.xbrl.org/2003/xbrl-linkbase-2003-12-31.xsd">
  <link:referenceLink xlink:type="extended" xlink:role="http://www.xbrl.org/2003/role/link">
    <link:loc xlink:type="locator" xlink:href="../core/in-ghi-rep.xsd#in-ghi-rep_ReportingPeriodTable" xlink:label="in-ghi-rep_ReportingPeriodTable"/>
    <link:reference xlink:type="resource" xlink:label="res_1" xlink:role="http://www.xbrl.org/2003/role/disclosureRef" xlink:id="res_1">
      <in-ghi-rep-par:Circular>DBS.No.FBC.BC.34/13.12.001/99-2000  dt April 6, 2000</in-ghi-rep-par:Circular>
    </link:reference>
  </link:referenceLink>
</link:linkbase>

上面的文本是生成的,但是当我写入文件时,它只是写入Circular 标签。我在这里找不到我做错了什么。有什么帮助吗?

【问题讨论】:

标签: python xml-parsing elementtree


【解决方案1】:

基于docs tree.write() 是你想要的。在你的情况下,我认为 root.write("s.txt", encoding="utf-8") 应该这样做(我没有测试它)。

【讨论】:

  • et = etree.ElementTree(root) with open('samp.txt', 'wb') as f: et.write(f, encoding="utf-8", xml_declaration=True, pretty_print=True)。这做到了。谢谢
  • 答案不是准确的答案。不过我明白了。
猜你喜欢
  • 1970-01-01
  • 2021-01-26
  • 1970-01-01
  • 2016-02-10
  • 2020-07-05
  • 2011-08-30
  • 1970-01-01
  • 2022-11-27
  • 1970-01-01
相关资源
最近更新 更多