我正在尝试使用 ElementTree 从 NuGet 包的 .targets 文件中解析信息。 我试图找到的是标签
<AdditionalIncludeDirectories>
。我正在使用以下 python 代码来尝试获取它:
import xml.etree.ElementTree as ET
tree = ET.parse(targets_file_path)
config_root = tree.getroot()
namespace = config_root.tag.replace("Project", "")
to_find = f"{namespace}AdditionalIncludeDirectories"
include_dirs = config_root.findall(to_find)
include_directory_list = []
for p in include_dirs:
include_directory_list.append(p)
这本质上是 python 文档 中的第一个示例。然而,在我执行此代码片段后,列表
include_directory_list
是空的。
但是,当我打印每个标签时,我得到以下输出:
depth = 0
item_list = []
for it in config_root:
item_list.append([depth, it])
while len(item_list) > 0:
d, it = item_list.pop(0)
print(f"depth {d}: {it.tag}")
for subit in it:
item_list.append([d+1, subit])
产量:
depth 0: {http://schemas.microsoft.com/developer/msbuild/2003}PropertyGroup
depth 0: {http://schemas.microsoft.com/developer/msbuild/2003}ItemDefinitionGroup
depth 0: {http://schemas.microsoft.com/developer/msbuild/2003}ItemDefinitionGroup
depth 1: {http://schemas.microsoft.com/developer/msbuild/2003}ClCompile
depth 1: {http://schemas.microsoft.com/developer/msbuild/2003}Link
depth 1: {http://schemas.microsoft.com/developer/msbuild/2003}Link
depth 2: {http://schemas.microsoft.com/developer/msbuild/2003}AdditionalIncludeDirectories
depth 2: {http://schemas.microsoft.com/developer/msbuild/2003}AdditionalDependencies
depth 2: {http://schemas.microsoft.com/developer/msbuild/2003}AdditionalLibraryDirectorie
depth 2: {http://schemas.microsoft.com/developer/msbuild/2003}AdditionalDependencies
depth 2: {http://schemas.microsoft.com/developer/msbuild/2003}AdditionalLibraryDirectories
这正是我期望的输出。第一个深度 = 2 的项目是我正在寻找的项目,并且名称似乎是我输入到
findall()
的项目。我也尝试了iterfind()
,但这也没有给我正确的输出。还有传递命名空间字典的选项,我也尝试过,得到了相同的结果。
我感觉我要么看到了错误,要么错过了一些非常非常明显的东西。
任何帮助将不胜感激!
PS: XML 如下所示:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemDefinitionGroup>
<ClCompile>
<AdditionalIncludeDirectories>$(MSBuildThisFileDirectory)native\include\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup>
<Link Condition="'$(Configuration)'=='Debug'">
<AdditionalDependencies>mylib_d.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>$(MSBuildThisFileDirectory)native\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<Link Condition="'$(Configuration)'=='Release'">
<AdditionalDependencies>mylib.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>$(MSBuildThisFileDirectory)native\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
</Project>
您必须定义命名空间,然后才能使用
find()
进行搜索:
ns = {'': 'http://schemas.microsoft.com/developer/msbuild/2003'}
print(root.find(".//AdditionalIncludeDirectories", ns).text)
输出:
$(MSBuildThisFileDirectory)native\include\;%(AdditionalIncludeDirectories)