Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
XPath:如何根据元素的值选择元素?_Xpath - Fatal编程技术网

XPath:如何根据元素的值选择元素?

XPath:如何根据元素的值选择元素?,xpath,Xpath,我不熟悉使用XPath,这可能是一个基本问题。请容忍我,帮助我解决这个问题。我有这样一个XML文件: <RootNode> <FirstChild> <Element attribute1="abc" attribute2="xyz">Data</Element> <FirstChild> </RootNode> 使用后一个表达式时,会出现以下错误: 断言失败消息:没有匹配的节点//元素[@attribut

我不熟悉使用XPath,这可能是一个基本问题。请容忍我,帮助我解决这个问题。我有这样一个XML文件:

<RootNode>
  <FirstChild>
    <Element attribute1="abc" attribute2="xyz">Data</Element>
  <FirstChild>
</RootNode>
使用后一个表达式时,会出现以下错误:

断言失败消息:没有匹配的节点
//元素[@attribute1=“abc”和@attribute2=“xyz”和数据]

请告诉我我使用的XPath表达式是否有效。如果不是,有效的XPath表达式是什么?

以下条件:

//Element[@attribute1="abc" and @attribute2="xyz" and Data]
检查元素中是否存在元素数据,而不是元素值数据

相反,你可以使用

//Element[@attribute1="abc" and @attribute2="xyz" and text()="Data"]
我之所以添加此答案,是因为我想解释
text()
之间的关系

首先,当使用
[]
时,只有两种类型的数据:

  • [number]
    从节点集中选择节点
  • [bool]
    从节点集中筛选节点集
  • 在这种情况下,通过函数
    boolean()
    将该值计算为布尔值,并且有一条规则:

    过滤器总是根据上下文进行计算

    当您需要将
    text()
    与字符串
    “Data”
    进行比较时,它首先使用
    string()
    函数将其转换为字符串类型,然后得到布尔结果

    关于
    string()
    ,有两条重要规则:

  • string()
    函数通过返回节点集中第一个节点的字符串值将节点集转换为字符串,在某些情况下可能会产生意外结果

    text()
    是返回包含当前节点(上下文节点)的所有文本节点的节点集的相对路径,如
    [“数据”]
    。 当通过
    字符串([“Data”])
    对其求值时,它将返回节点集的第一个节点,因此只有当节点集中只有一个文本节点时,您才能获得“Data”

  • 如果希望
    string()
    函数连接所有子文本,则必须传递单个节点,而不是节点集

    例如,我们得到一个节点集
    ['a','b']
    ,您可以将该节点的父节点传递给
    字符串(父节点)
    ,这将返回
    'ab'
    ,当然
    字符串(.)
    在您的情况下将返回一个连接字符串
    “数据”

  • 只有当存在文本节点时,两种方法才能得到相同的结果

    //Element[@attribute1="abc" and @attribute2="xyz" and Data]
    
    //Element[@attribute1="abc" and @attribute2="xyz" and text()="Data"]
    
    //Element[@attribute1="abc" and @attribute2="xyz" and .="Data"]