Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use wildcard to match attribute in xpath

Tags:

asp.net

xpath

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

And I meet some problems when I process the XML.

Suppose I have XML like this:

<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 do I use xpath to implement it?

I only know this expression will match the person whose name is exactly "yx":

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

How to make the fuzzy search?

BTW, any idea to sort the matched person by the specified attribute like "name"?

like image 941
hguser Avatar asked Jul 09 '12 10:07

hguser


People also ask

Can we use wildcard in XPath?

XPATH allows the use of wildcards to write more robust path expressions where the use of specific path expressions is either impossible or undesirable. matches any element node.

What does the wildcard operator * Do in XPath?

xml file to learn XPath wildcards and its style sheet which uses Xpath expressions to select a value from the elements. The most widely used type is the asterisk(*). To match all nodes below expression is used and the (//) operator denotes a descendant type wildcard.

What does asterisk mean in XPath?

We generally use an asterisk (*) while writing XPaths. This is called a Wildcard character. An asterisk in XPath may represent any node or attribute name of XML or DOM. A node is a tag in XML document.


1 Answers

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

XPath itself is, at least at my knowledge, not capable and not intended to provide order on nodes, but instead returns node-sets which are "unordered collection of nodes without duplicates" (see 1 and comments). However in version 2.0 there might be changes to this 2 with which I am not familiar.

Assuming the sorting should be done in an XSL transformation you could use <xsl:sort /> like this:

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

There are some more attributes on <xsl:sort /> documented here: http://www.w3.org/TR/xslt#sorting

like image 109
hielsnoppe Avatar answered Sep 26 '22 03:09

hielsnoppe