【问题标题】:Parsing vcxproj with python and lxml用 python 和 lxml 解析 vcxproj
【发布时间】:2016-09-16 14:27:35
【问题描述】:

我正在尝试使用 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)

如果我这样运行,脚本可以运行但什么也不显示。如果我在节点 Project 脚本中删除 DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" 脚本有效...

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

感谢您的帮助。

【问题讨论】:

    标签: python xml vcxproj


    【解决方案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)
    

    【讨论】:

    • 这确实是最好的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    • 1970-01-01
    • 2012-08-08
    • 2013-10-01
    • 2010-12-07
    • 2012-06-10
    • 1970-01-01
    相关资源
    最近更新 更多