简体   繁体   中英

Python: xml.Find always returns none

So I'm trying to search and replace the xml keyword RunCodeAnalysis inside a vcxproj file with python. I'm pretty new to python so be gentle, but I thought it would be the simplest language to do this kind of thing. 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.

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

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. 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. 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.

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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