Reputation: 241
Here is a sample XML file:
<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>
The above XML file is based on the template of Visual Studio's sqlproj file. It is distinguished based on what kind of nodes are inside.
My research:
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.
I want to add <Folder Include="newpath" />
and <Folder Include="newsql" />
into appropriate ItemGroup using Python's xml.dom.minidom library, and eventually override the original sqlproj file.
How to do that?
If you suggest other built-in libraries, please give an example, thanks.
Upvotes: 2
Views: 4081
Reputation: 474191
You didn't tell enough info on how to distinguish ItemGroup
s between each other, but I'm assuming it is based on what kind of nodes are inside.
Here's how you can insert new Folder
tags into the ItemGroup
of Folder
s and None
s. The idea is to find the first Folder
and None
tags, get the parent and appendChild
to it:
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()
It prints:
<?xml version="1.0" ?>
<Project attri1="build">
<Import Project="blahblah" xmlns="someURI"/>
<ItemGroup>
<Folder Include="Scripts"/>
<Folder Include="Scripts/1.0"/>
<Folder Include="Scripts/2.0/"/>
<Folder Include="newpath"/>
</ItemGroup>
<ItemGroup/>
<ItemGroup>
<None Include="Scripts/1.0/001.sql"/>
<None Include="Scripts/2.0/002.sql"/>
<Folder Include="newsql"/>
</ItemGroup>
</Project>
Upvotes: 3