Print all xml child node using python

一笑奈何 提交于 2019-12-02 03:49:35

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:

  • I ran the code with Python 3.4 (since no version was mentioned in the question). 2.7 compatibility will require some minor changes.
  • I did my tests on a VStudio project where the second search tag was ClInclude, but I guess that's an fairly old version.
  • The 1stprint line is only for illustrating the parent ItemGroup node. Comment it out to achieve your desired output.
  • Needless to say that you should modify project_path to point to your project file.

An alternate solution using ElementTree,

import xml.etree.ElementTree as ET
root = ET.fromstring('''\
<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>
''')

for child in root.iter('ClCompile'):
    print ET.tostring(child)

While parsing from file,

import xml.etree.ElementTree as ET
tree=ET.parse('text.xml')
root = tree.getroot()
for child in root.iter('ClCompile'):
    print ET.tostring(child)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!