使用Python minidom修改XML

时间:2014-05-01 16:19:29

标签: python xml dom minidom

以下是XML文件示例:

<Project attri1="build">
    <Import Project="blahblah" xmlns="someURI" />
    <Property>
        ...
    </Property>
    <Property>
        ...
    </Property>
    ...
    <ItemGroup>
        <Folder Include="Scripts" />
        <Folder Include="Scripts/1.0" />
        <Folder Include="Scripts/2.0/" />
        ...
    </ItemGroup>
      ... some irrelevant ItemGroup is here
    <ItemGroup>
         <None Include="Scripts/1.0/001.sql" />
         <None Include="Scripts/2.0/002.sql" />
    </ItemGroup>
    ...
</Project>

上述XML文件基于Visual Studio的sqlproj文件模板。它根据内部的节点类型进行区分。


我的研究:

import xml.dom.minidom
sql = xml.dom.minidom.parse('file.sqlproj')
itemGroup = sql.getElementsByTagName('ItemGroup')
folderGroup = itemGroup[0] # The first ItemGroup has folders
sqlGroup = itemGroup[2] # The 3rd ItemGroup has sql file list.

我想使用Python的xml.dom.minidom库将<Folder Include="newpath" /><Folder Include="newsql" />添加到适当的ItemGroup中,并最终覆盖原始的sqlproj文件。

怎么做?

如果您推荐其他内置库,请举例,谢谢。

1 个答案:

答案 0 :(得分:2)

你没有告诉我们如何区分ItemGroup彼此之间的足够信息,但我认为它是基于内部的节点类型。

以下是在FolderItemGroup的{​​{1}}中添加新Folder代码的方法。我们的想法是找到第一个NoneFolder代码,获取父代和None代码:

appendChild

打印:

import xml.dom.minidom

data = """<Project attri1="build">
    <Import Project="blahblah" xmlns="someURI" />
    <ItemGroup>
        <Folder Include="Scripts" />
        <Folder Include="Scripts/1.0" />
        <Folder Include="Scripts/2.0/" />
    </ItemGroup>
    <ItemGroup/>
    <ItemGroup>
         <None Include="Scripts/1.0/001.sql" />
         <None Include="Scripts/2.0/002.sql" />
    </ItemGroup>
</Project>"""

dom = xml.dom.minidom.parseString(data)

new_folder = dom.createElement('Folder')
new_folder.setAttribute('Include', 'newpath')

folder = dom.getElementsByTagName('Folder')[0]
folder.parentNode.appendChild(new_folder)

new_script = dom.createElement('Folder')
new_script.setAttribute('Include', 'newsql')

none = dom.getElementsByTagName('None')[0]
none.parentNode.appendChild(new_script)

print dom.toprettyxml()