使用python和lxml解析vcxproj

时间:2016-05-19 15:27:10

标签: python xml vcxproj

我试图用Python和lxml解析vcxproj。当我尝试这样做时,除非我删除<Project >中的内容,否则在打印过程中不会显示任何内容。

这是我的.vcxproj(我将其缩减为测试):

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup Label="ProjectConfigurations">
    <ProjectConfiguration Include="Debug|Win32">
      <Configuration>Debug</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Debug|x64">
      <Configuration>Debug</Configuration>
      <Platform>x64</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="ReleaseDebug|Win32">
      <Configuration>ReleaseDebug</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="ReleaseDebug|x64">
      <Configuration>ReleaseDebug</Configuration>
      <Platform>x64</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Release|Win32">
      <Configuration>Release</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Release|x64">
      <Configuration>Release</Configuration>
      <Platform>x64</Platform>
    </ProjectConfiguration>
  </ItemGroup>
</Project>

我的python代码:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

from lxml import etree

tree = etree.parse("core.xml")

for conf in tree.xpath("/Project/ItemGroup/ProjectConfiguration/Configuration"):
    print(conf.text)

如果我像这样运行,脚本可以正常工作但不显示任何内容。如果我删除节点项目脚本中的DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"脚本...

我是xml的新手,也许我做错了什么。你可以帮我解决这个问题吗?

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

在此处找到解决方案:lxml etree xmlparser remove unwanted namespace

看来,我必须先使用精确的命名空间(如果有的话):

from lxml import etree

tree = etree.parse("core.xml")

namespaces = {'ns':'http://schemas.microsoft.com/developer/msbuild/2003'}
for conf in tree.xpath('//ns:Configuration', namespaces=namespaces):
    print (conf.text)