使用编写xml文件时出现的问题xml.dom.minidompython

2024-09-28 05:44:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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>

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

^{pr2}$

下面给出了我使用的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,我应该在代码中更新什么

谢谢


Tags: 模块文件代码importprojectxmlcommanddom
1条回答
网友
1楼 · 发布于 2024-09-28 05:44:21

来自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-module中的正则表达式并手动插入。在

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

^{pr2}$

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

相关问题 更多 >

    热门问题