我需要添加一个新标签并写回 XML。这是我的 XML 文件。
<?xml version="1.0" encoding="UTF-8"?>
<!--Arbortext, Inc., 1988-2011, v.4002-->
<!DOCTYPE reference-configuration-statement PUBLIC "-//Juniper Networks//DTD Jbook Software Guide//EN"
"file:////cmsxml/IWServer/default/main/TechPubsWorkInProgress/STAGING/bin/dtds/jbook-sw/jbook-sw.dtd">
<?Pub UDT _nopagebreak _touchup KeepsKeep="yes" KeepsPrev="no" KeepsNext="no" KeepsBoundary="page"?>
<?Pub UDT _bookmark _target?>
<?Pub UDT instructions _comment FontColor="red"?>
<?Pub UDT instructions-DUPLICATE1 _comment FontColor="red"?>
<?Pub UDT __target_1 _target?>
<?Pub UDT __target_3 _target?>
<?Pub UDT __target_2 _target?>
<?Pub UDT _bookmark-DUPLICATE1 _target?>
<?Pub UDT __target_4 _target?>
<?Pub EntList copy trade micro reg plusmn deg middot mdash ndash nbsp
caret cent check acute frac12 frac13 frac14 frac15 frac16 frac18 frac23
frac25 frac34 frac35 frac38 frac45 frac56 frac58 frac78 ohm pi sup sup1
sup2 sup3 rsquo?>
<?Pub Inc?>
<root topic-id="25775"
我能够用 etree 完成任务。
path="C:/Users/pshahul/Desktop/Official/Automation/Write_XMl_files/Source/"
add=(path, Filename)
myfile=s.join(add)
try:
et = xml.etree.ElementTree.parse(myfile)
tree=etree.parse(myfile)
docinfo=tree.docinfo.encoding
root=et.getroot()
elem = root.find('cli-help')
if elem is None:
new_tag=ET.Element("cli-help")
new_tag.text=final
root.insert(2,new_tag)
et.write(myfile,encoding=docinfo, xml_declaration=True)
else:
elem.text=final
et.write(myfile,encoding=docinfo, xml_declaration=True)
except OSError:
pass
else:
raise TypeError
except TypeError:
continue
现在,我得到了 DOCTYPE 和 XML 声明,但跳过了以下内容。
<!--Arbortext, Inc., 1988-2011, v.4002-->
<?Pub UDT _nopagebreak _touchup KeepsKeep="yes" KeepsPrev="no" KeepsNext="no" KeepsBoundary="page"?>
<?Pub UDT _bookmark _target?>
<?Pub UDT instructions _comment FontColor="red"?>
<?Pub UDT instructions-DUPLICATE1 _comment FontColor="red"?>
<?Pub UDT __target_1 _target?>
<?Pub UDT __target_3 _target?>
<?Pub UDT __target_2 _target?>
<?Pub UDT _bookmark-DUPLICATE1 _target?>
<?Pub UDT __target_4 _target?>
<?Pub EntList copy trade micro reg plusmn deg middot mdash ndash nbsp
caret cent check acute frac12 frac13 frac14 frac15 frac16 frac18 frac23
frac25 frac34 frac35 frac38 frac45 frac56 frac58 frac78 ohm pi sup sup1
sup2 sup3 rsquo?>
<?Pub Inc?>
我该如何保存它?我需要这些行回到我的 XML 文件中。加评论。我也发现评论不见了。