Use wildcard to match attribute in xpath

I am working on an asp.net application based on .net 2.0.

And I encounter some problems when processing XML.

Suppose I have XML:

<person name="xxxyx" age="32" /> <person name="zzz" age="32" /> <person name="yyyxx" age="32" /> 

Now I want to select the person whose name contains yx

How to use xpath to implement it?

I only know that this expression will correspond to the person whose name is exactly "yx":

 "//person[name='yx'"]" 

How to make a fuzzy search?

BTW, any idea to sort the matching person by the specified attribute, for example, "name"?

+8
xpath
source share
2 answers

Like @Utkanos, the proposed //person[contains(@name, 'yx')] should match the nodes you need.

XPath itself, at least as far as I know, is not capable and not designed to maintain order on nodes, but instead returns node-sets that are โ€œan unordered set of nodes without duplicatesโ€ (see 1 and comments). However, in version 2.0, changes to this 2 may occur that I am not familiar with.

Assuming sorting should be done in an XSL transform, you can use <xsl:sort /> as follows:

 <xsl:apply-templates select="//person[contains(@name, 'yx')]"> <xsl:sort select="@name" /> </xsl:apply-templates> 

There are several more attributes in <xsl:sort /> : http://www.w3.org/TR/xslt#sorting

+9
source share

Use the contains() function.

 //person[contains(@name, 'yx')] 

Also, note that you need @ in front of name , as this is an attribute.

Demo

+8
source share

All Articles