pythonxml-parsingelementtreeminidom

Print all xml child node using python


I want to print all the values of the "ClCompiler" child of "ItemGroup" of my xml file.

my python code

tree = minidom.parse(project_path)
itemgroup = tree.getElementsByTagName('ItemGroup')
print (itemgroup[0].toxml())

my result

<ItemGroup Label="ProjectConfigurations">
    <ProjectConfiguration Include="Debug|Win32">
        <Configuration>Debug</Configuration>
        <Platform>Win32</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Release|Win32">
        <Configuration>Release</Configuration>
        <Platform>Win32</Platform>
    </ProjectConfiguration>
</ItemGroup>
<ItemGroup>
    <ClCompile Include="../../avmedia/source/framework/MediaControlBase.cxx"/>
    <ClCompile Include="../../avmedia/source/framework/mediacontrol.cxx"/>
    <ClCompile Include="../../avmedia/source/framework/mediaitem.cxx"/>
    <ClCompile Include="../../avmedia/source/framework/mediamisc.cxx"/>
</ItemGroup>

ecc


expected result

    <ClCompile Include="../../basic/source/basmgr/basmgr.cxx"/>         
    <ClCompile Include="../../basic/source/basmgr/vbahelper.cxx"/>      
    <ClCompile Include="../../basic/source/classes/codecompletecache.cxx"/>

ecc


part of my xml

<ItemGroup>
    <ClCompile Include="../../basic/source/basmgr/basicmanagerrepository.cxx"/>
    <ClCompile Include="../../basic/source/basmgr/basmgr.cxx"/>
    <ClCompile Include="../../basic/source/basmgr/vbahelper.cxx"/>
    <ClCompile Include="../../basic/source/classes/codecompletecache.cxx"/>
</ItemGroup>

Solution

  • You made it half way.
    You found all the ItemGroup nodes in the document. Now, you have to iterate through each of them and find its ClCompile children (most likely only one of them will have such children).

    Here's the code:

    from xml.dom import minidom
    
    project_path = "./a.vcxproj"
    item_group_tag = "ItemGroup"
    cl_compile_tag = "ClCompile"
    
    
    def main():
        tree = minidom.parse(project_path)
        item_group_nodes = tree.getElementsByTagName(item_group_tag)
        for idx, item_group_node in enumerate(item_group_nodes):
            print("{} {} ------------------".format(item_group_tag, idx))
            cl_compile_nodes = item_group_node.getElementsByTagName(cl_compile_tag)
            for cl_compile_node in cl_compile_nodes:
                print("\t{}".format(cl_compile_node.toxml()))
    
    
    if __name__ == "__main__":
        main()
    

    Notes: