【发布时间】:2016-02-03 10:32:48
【问题描述】:
这是 jenkins xml 文件的一部分。
我想用xpath提取project_name的defaultValue。
在这种情况下,值为*****。
<?xml version='1.0' encoding='UTF-8'?>
<project>
<properties>
<hudson.model.ParametersDefinitionProperty>
<parameterDefinitions>
<hudson.model.StringParameterDefinition>
<name>customer_name</name>
<description></description>
<defaultValue>my_customer</defaultValue>
</hudson.model.StringParameterDefinition>
<hudson.model.StringParameterDefinition>
<name>project_name</name>
<description></description>
<defaultValue>*****</defaultValue>
</hudson.model.StringParameterDefinition>
</parameterDefinitions>
</hudson.model.ParametersDefinitionProperty>
</properties>
</project>
我使用 python 的 etree,但是 AFAIK 这并不重要,因为这是一个 xpath 问题。
我目前的 xpath 知识有限。我目前的做法:
for name_tag in config.findall('.//name'):
if name_tag.text=='project_host':
default=name_tag.getparent().findall('defaultValue')[0].text
我在这里得到AttributeError: 'Element' object has no attribute 'getparent'
我又想到了这个,我认为在python中循环是错误的方法。这应该可以通过 xpath 选择。
【问题讨论】:
-
请同时展示您的 Python 代码并解释您的方法为何无法按预期工作。谢谢。更多帮助:stackoverflow.com/help/mcve.
-
etree 仅支持有限的 XPath 1.0 子集:19.7.2.2. Supported XPath syntax。如果您想广泛使用 XPath,请使用
lxml -
@MathiasMüller 我添加了我当前的解决方案。
-
@har07 我可以安装lxml,没问题。但是到目前为止我还不知道 xpath 魔法本身。
-
在 XPath 中,您可以使用谓词表达式(包含在
[]中的表达式)过滤上下文元素,即[]之前的元素,具有特定条件,就像下面的答案所示。跨度>
标签: python xml xpath jenkins elementtree