本文介绍了Xpath 通配符搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 xpath 查询在所有节点和所有属性中搜索特定文本.

I want to search within all nodes and all attributes for a specific text using xpath query.

示例:

<Employee>
  <Id>1</Id>
  <Info FirstName="Search" LastName="Smith">
    <Address City="Search"/>
  </Info>
</Employee>

我目前正在使用以下 xpath 查询:

I am currently using the below xpath query:

var nodes = xmlConfig.SelectNodes("//*[contains(@*,'Search')]");

Xpath 查询应返回信息节点和地址节点.但是,它只返回一个节点.

Xpath query should return Info node and Address node. However, it only returns one node.

推荐答案

假设您使用的是 XPath 1.0,您的 XPath 应该已经返回了 Info 节点和 Address 节点如你所料.请参阅以下链接中的在线演示(单击测试"按钮以执行 XPath):

Assuming that you're using XPath 1.0, your XPath should have returned Info node and Address node as you expect. See online demo for that in the following link (click on 'test' button to execute the XPath) :

//*[contains(@*,'Search')]

在 XPath 2.0 中,上述将抛出异常 不允许将多个项目的序列作为 contains() 的第一个参数,这是因为一个元素可能有多个属性.对于 XPath 2.0 兼容表达式,您可以这样做:

In XPath 2.0, the above will throw exception passing sequence of more than one item is not allowed as the first argument of contains(), and that happen because one element may have more than one attribute. For XPath 2.0 compatible expression, you can do this way instead :

//*[@*[contains(.,'Search')]]

输出:

<Info FirstName="Search" LastName="Smith">
    <Address City="Search"/>
  </Info>

<Address City="Search"/>

这篇关于Xpath 通配符搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 23:23