【问题标题】:ElementTree find returns None even without xmlns即使没有 xmlns,ElementTree find 也会返回 None
【发布时间】:2019-12-12 08:20:05
【问题描述】:

我正在尝试在 Python 2.7.5 中使用没有 xmlns 的 ElementsTree 替换 XML 中的一些值,但无论如何它总是返回 None。

这是我的 truncated.xml:

<?xml version='1.0' encoding='UTF-8'?>
<definition>
    <scm>
        <configVersion>2</configVersion>
        <userRemoteConfigs>
            <hudson.plugins.git.UserRemoteConfig>
                <url>git@github.company.com:org/repository.git</url>
                <credentialsId>abcdefgh-123456-7890</credentialsId>
            </hudson.plugins.git.UserRemoteConfig>
        </userRemoteConfigs>
        <branches>
            <hudson.plugins.git.BranchSpec>
                <name>refs/heads/master</name>
            </hudson.plugins.git.BranchSpec>
        </branches>
        <doGenerateSubmoduleConfigurations>false</doGenerateSubmoduleConfigurations>
        <submoduleCfg/>
        <extensions/>
    </scm>
    <scriptPath>Jenkinsfile</scriptPath>
    <lightweight>true</lightweight>
</definition>

这是我在 test.py 中的代码:

from xml.etree import ElementTree as et
tree = et.parse('truncated.xml')
print(tree.find('definition/scm/userRemoteConfigs/hudson.plugins.git.UserRemoteConfig/url'))
tree.find('definition/scm/userRemoteConfigs/hudson.plugins.git.UserRemoteConfig/url').text = '<replacement text>'

输出:

None
Traceback (most recent call last):
  File "test.py", line 4, in <module>
    tree.find('definition/scm/userRemoteConfigs/hudson.plugins.git.UserRemoteConfig/url').text = '<replacement text>'
AttributeError: 'NoneType' object has no attribute 'text'

【问题讨论】:

    标签: xml python-2.7 elementtree nonetype


    【解决方案1】:

    当您构建树时,上下文已经是definition。尝试将 definition/ 从您的 xpath 前面去掉...

    tree.find('scm/userRemoteConfigs/hudson.plugins.git.UserRemoteConfig/url')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-13
      • 2021-05-26
      • 2019-06-22
      • 2021-04-02
      • 1970-01-01
      相关资源
      最近更新 更多