如果使用python不存在,请在文件中添加一行

时间:2012-09-05 05:56:20

标签: python xml

我有一个xml文件,如下所示:

<?xml version="1.0" encoding="utf-8"?>
  <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build" ToolsVersion="4.0">
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
  <ImportGroup Label="ExtensionTargets">
  </ImportGroup>
</Project>

我想在之间添加一行<Import Project="$(ProjectName).targets" /> </ImportGroup></Project>如下

<?xml version="1.0" encoding="utf-8"?>
  <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build" ToolsVersion="4.0">
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
  <ImportGroup Label="ExtensionTargets">
  </ImportGroup>
  <Import Project="$(ProjectName).targets" />
</Project>

如果文件中已存在行<Import Project="$(ProjectName).targets" />,则无需添加。

我该怎么做?

2 个答案:

答案 0 :(得分:2)

使用您选择的XML解析器,解析文件,使用相关API处理文件,然后将其写回。

答案 1 :(得分:2)

您的问题是基于文本文件中的行,但输入文件显然是XML,因此假设您实际上想要添加导入(如果它不存在),请尝试以下操作:

import xml.dom.minidom

importstring = "$(Projectname).targets"
filename = "test.xml"

tree = xml.dom.minidom.parse(filename)
Project = tree.getElementsByTagName("Project")[0]

for Import in Project.getElementsByTagName("Import"):
    if Import.getAttribute("Project") == importstring:
        break
else: # note this is else belongs to the for, not the if
    newImport = xml.dom.minidom.Element("Import")
    newImport.setAttribute("Project", importstring)
    Project.appendChild(newImport)

tree.writexml(open(filename, 'w'))