我想打印我的xml文件的“ItemGroup”的“ClCompiler”子项的所有值。
tree = minidom.parse(project_path)
itemgroup = tree.getElementsByTagName('ItemGroup')
print (itemgroup[0].toxml())
<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
<ClCompile Include="../../basic/source/basmgr/basmgr.cxx"/>
<ClCompile Include="../../basic/source/basmgr/vbahelper.cxx"/>
<ClCompile Include="../../basic/source/classes/codecompletecache.cxx"/>
ECC
<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>
答案 0 :(得分:1)
你做到了一半。
你在文档中找到了所有 ItemGroup 节点。现在,你必须遍历每一个并找到它的 ClCompile 子项(很可能只有其中一个会有这样的孩子)。
以下是代码:
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()
备注强>:
print
行仅用于说明父 ItemGroup 节点。注释它以达到您想要的输出。project_path
以指向您的项目文件。答案 1 :(得分:0)
使用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)
从文件解析时,
import xml.etree.ElementTree as ET
tree=ET.parse('text.xml')
root = tree.getroot()
for child in root.iter('ClCompile'):
print ET.tostring(child)