这是jenkins xml文件的一部分。在
我想用xpath提取project_name
的默认值。在
在这种情况下,值是*****
。在
<?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,但这并不重要,因为这是一个xpath问题。在
我目前的xpath知识有限。我目前的做法是:
^{pr2}$这里我得到AttributeError: 'Element' object has no attribute 'getparent'
我又考虑过这个问题,我认为在python中循环是错误的方法。这应该可以通过xpath选择。在
您可以尝试lxml.etree如下-我使用循环来选择具有相同位置的所有节点。在
所需xpath的示例是-我使用了relative xpath,因为它在长节点路径的情况下非常有用。在
.//hudson.model.StringParameterDefinition/name[contains(text(),'project_name')]/following-sibling::defaultValue
或者
^{pr2}$
输出-
问题的答案就是XPath
它将选择作为唯一的结果
^{pr2}$假设您的实际文档没有命名空间。您不需要访问父元素或同级轴。在
即使etree也应该支持这种XPath表达式,但它可能不支持comment by har07。在
是的,我同意。如果要从文档中选择单个值,请使用XPath表达式选择该值,并将其直接存储为Python字符串,而不必循环使用元素。在
使用lxml的完整示例
输出:
^{pr2}$相关问题 更多 >
编程相关推荐