【发布时间】:2017-12-26 16:20:57
【问题描述】:
我需要添加一个新标签并写回一个 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 文件中。加上cmets。我发现 cmets 也不见了。
【问题讨论】:
-
您只发布了部分代码和错误。查看[SO]: How to ask 或[SO]: mcve 了解更多询问相关详情。您的第一个 sn-p 中的缩进是错误的(最后一个
else)。此外,缩进代码时使用 4 个 SPACE,而不是 TAB。 -
完全不清楚你想要什么。请提供minimal reproducible example。
-
我已经把我的整个代码放在这里了。我的问题是 1. 如何保存 DOCTYPE 2. 如何更改 lt;和GT;到
-
问题还是不太清楚。当我们要求minimal reproducible example 时,我们并不是要求您提供整个代码。我们要求重现问题的最小代码段。你应该删除所有不需要的东西。
-
其实我是个白痴。使用 lxml 但使用 ET 编写。我使用了 lxml,它保留了所有内容。一个美容错误花了我几个小时。抱歉,感谢您的回答。
标签: python xml-parsing comments lxml processing-instruction