简体   繁体   English

Python:xml.Find总是不返回

[英]Python: xml.Find always returns none

So I'm trying to search and replace the xml keyword RunCodeAnalysis inside a vcxproj file with python. 因此,我正在尝试使用python搜索并替换vcxproj文件中的xml关键字RunCodeAnalysis。 I'm pretty new to python so be gentle, but I thought it would be the simplest language to do this kind of thing. 我是python的新手,所以要谦虚一些,但是我认为这是做这种事情的最简单的语言。 I read a handful of similar examples and came up with the code below, but no matter what I search for the ElementTree Find call always returns None. 我阅读了一些类似的示例,并给出了以下代码,但是无论我搜索ElementTree Find调用什么,总是返回None。

from xml.etree import ElementTree as et

xml = '''\
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Protected_Debug|Win32'">
      <RunCodeAnalysis>false</RunCodeAnalysis>
   </PropertyGroup>
</Project>
'''

et.register_namespace('', "http://schemas.microsoft.com/developer/msbuild/2003")
tree = et.ElementTree(et.fromstring(xml))
print(tree.find('.//RunCodeAnalysis'))

Here's a simplified code example online: https://ideone.com/1T1wsb 这是在线的简化代码示例: https : //ideone.com/1T1wsb

Can anyone tell me what I'm doing wrong? 谁能告诉我我在做什么错?

Ok.. So @ThomWiggers helped me with the missing piece - and here's my final code in all it's naive glory. 好的,所以@ThomWiggers帮助我解决了丢失的部分-这是我天真的荣耀中的最终代码。 No parameter checking or any kind of smarts yet, but it takes two parameters - filename and whether to turn static code analysis to true or false. 尚无参数检查或任何类型的智能功能,但它需要两个参数-文件名以及是否将静态代码分析转换为true或false。 I've got about 30 projects I want to turn it on for for nightly builds but really don't want to turn it on day to day as it's just too slow. 我有大约30个项目,我想将其打开以进行每晚构建,但真的不想每天都打开它,因为它太慢了。

import sys
from xml.etree import ElementTree as et

et.register_namespace('', "http://schemas.microsoft.com/developer/msbuild/2003")
tree = et.parse(sys.argv[1])
value = sys.argv[2]
for item in tree.findall('.//{http://schemas.microsoft.com/developer/msbuild/2003}RunCodeAnalysis'):
    item.text = value
for item in tree.findall('.//{http://schemas.microsoft.com/developer/msbuild/2003}EnablePREfast'):
    item.text = value
tree.write(sys.argv[1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM