我正在处理我想要插入到固定部分中的现有文件中的特定数据集。我想改变XML文件,如下所示:
<SBEDataUploadFile>
<ApplicationData>
<firmware>
<SoftwareVersion>1.0</SoftwareVersion>
<BuildDate>Dec 1 2012 10:43:42</BuildDate>
</firmware>
</ApplicationData>
</SBEDataUploadFile>
看起来像这样:
<SBEDataUploadFile>
<![CDATA[
** Location 001
** Latitude In 18.33885
** Longitude In 64.97647
** Time In 11:55
** Depth (ft) 10
** Line Out (ft) 5
** Time Out 11:56
** Latitude Out 18.33885
** Longitude Out 64.97647
** Notes
]]>
<ApplicationData>
<firmware>
<SoftwareVersion>1.0</SoftwareVersion>
<BuildDate>Dec 1 2012 10:43:42</BuildDate>
</firmware>
</ApplicationData>
</SBEDataUploadFile>
我使用xml.etree.ElementTree
尝试了此操作,但我的结果是它在</ApplicantionData>
之后将注释附加到底部。这是我目前的代码:
import xml.etree.ElementTree as ET
#variables
location = "BPT"
latitude_in = 0
longitude_in = 0
time_in = 0
depth = 0
line_out = 0
time_out = 0
latitude_out = 0
longitude_out = 0
notes = ""
#formatting and converting all variables to string
toString = "<![CDATA["+"\n"+"** Location "+location+"\n"+"** Latitude In "\
+str(latitude_in)+"\n"+"** Longitude In "+str(longitude_in)+"\n"+\
"** Time In "+str(time_in)+"\n"+"** Depth (ft) "+str(depth)+"\n"+"** Line Out (ft) "\
+str(line_out)+"\n"+"** Time Out "+str(time_out)+"\n"+"** Latitude Out "\
+str(latitude_out)+"\n"+"** Longitude Out "+str(longitude_out)+"\n"+"** Notes "+notes+"\n"+"]]>"
xml_filepath = xmlfilepath.xml
xml_tree = ET.parse(xml_filepath)
xml_root = xml_tree.getroot()
ET.SubElement(xml_root, toString)
print ET.tostring(xml_root)
这些是我目前的结果:
<SBEDataUploadFile>
<ApplicationData>
<firmware>
<SoftwareVersion>1.0</SoftwareVersion>
<BuildDate>Dec 1 2012 10:43:42</BuildDate>
</firmware>
</ApplicationData>
<<![CDATA[
** Location BPT
** Latitude In 0
** Longitude In 0
** Time In 0
** Depth (ft) 0
** Line Out (ft) 0
** Time Out 0
** Latitude Out 0
** Longitude Out 0
** Notes
]]> /></SBEDataUploadFile>
我希望这能使它看起来像我想要的结果,并在/>
之前摆脱额外的</SBEDataUploadFile>
。
答案 0 :(得分:0)
您不需要SubElement
。只需在根元素上设置文本节点:
xml_root.text = toString