【发布时间】: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 ../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 标签。我在这里找不到我做错了什么。有什么帮助吗?
【问题讨论】:
-
这能回答你的问题吗? Write xml file using lxml library in Python
-
不,它给出了相同的输出,即只有
Circular标签被写入文件。
标签: python xml-parsing elementtree