Skip to main content
 首页 » 编程设计

python之使用 xml.dom.minidom python 编写 xml 文件时的问题

2025年05月04日11tintown

我有一个 xml 文件,一个 python 脚本用于向该 xml 文件添加一个新节点。我使用 xml.dom.minidom 模块处理 xml 文件。使用 python 模块处理后的 xml 文件如下所示

<?xml version="1.0" ?><Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> 
<PostBuildEvent> 
  <Command>xcopy &quot;SourceLoc&quot; &quot;DestLoc&quot;</Command> 
</PostBuildEvent> 
<ImportGroup Label="ExtensionTargets"> 
</ImportGroup> 
<Import Project="project.targets"/></Project> 

我实际需要的是如下所示。更改是第一行之后和最后一行之前的换行符,并且 '"' 转换为 "

<?xml version="1.0" ?> 
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> 
<PostBuildEvent> 
  <Command>xcopy "SourceLoc" "DestLoc"</Command> 
</PostBuildEvent> 
<ImportGroup Label="ExtensionTargets"> 
</ImportGroup> 
<Import Project="project.targets"/> 
</Project> 

下面给出了我使用的python代码

xmltree=xml.dom.minidom.parse(xmlFile) 
for Import in Project.getElementsByTagName("Import"): 
   newImport = xml.dom.minidom.Element("Import") 
   newImport.setAttribute("Project", "project.targets") 
vcxprojxmltree.writexml(open(VcxProjFile, 'w')) 

我应该在我的代码中更新什么以获得正确格式的 xml

谢谢,

请您参考如下方法:

来自 minidom 的文档:

Node.toprettyxml([indent=""[, newl=""[, encoding=""]]]) 
 
Return a pretty-printed version of the document. indent specifies the indentation string and defaults to a tabulator; newl specifies the string emitted at the end of each line and defaults to \n. 

这就是您从 minidom 获得的所有定制。

尝试插入一个文本节点作为换行符的根兄弟节点。希望不灭。 我建议使用 re 模块中的正则表达式并手动插入。

至于删除 SGML 实体,python 标准库中显然有一个未记录的函数:

import HTMLParser 
h = HTMLParser.HTMLParser() 
unicode_string = h.unescape(string_with_entities) 

或者,您可以再次使用 re 手动执行此操作,因为所有命名实体名称和相应的代码点都在 htmlentitydefs 模块中。