Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><em>The previous two answers seem to be not exact</em>.</p> <p><strong>Here is one possible solution</strong>:</p> <p>You want to find the first node with the maximum value for the following function:</p> <pre><code>100*number(@text='Login') +10*number(@href='Login.php') + 1*number(@index=0) </code></pre> <p><strong>In XPath 2.0</strong> this can be expressed as a single XPath expression in the following way:</p> <pre><code> /*/link[ 100*number(@text='Login') +10*number(@href='Login.php') + 1*number(@index=0) eq max(/*/link /(100*number(@text='Login') +10*number(@href='Login.php') + 1*number(@index='0') ) ) ] </code></pre> <p><strong>In XPath 1.0 constructing such a one-lener expression would be extremely difficult</strong>, if possible at all, and even if possible, such an XPath expression will be impossible to understand, prove correct and/or maintain.</p> <p>However, <em>selecting the best-matching <code>link</code> element is possible within any language that is a host of XPath 1.0</em>. </p> <p><strong>One example below is with XSLT 1.0</strong> as the hosting language:</p> <pre><code>&lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt; &lt;xsl:output omit-xml-declaration="yes" indent="yes"/&gt; &lt;xsl:template match="/"&gt; &lt;xsl:for-each select="*/link"&gt; &lt;xsl:sort data-type="number" order="descending" select= "100*(@text='Login') +10*(@href='Login.php') + 1*(@index=0) "/&gt; &lt;xsl:if test="position() = 1"&gt; &lt;xsl:copy-of select="."/&gt; &lt;/xsl:if&gt; &lt;/xsl:for-each&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p><strong>when the above transformation is applied on this XML document</strong>:</p> <pre><code>&lt;links&gt; &lt;link name="A" text="Sign in" href="Login.php" index="0"/&gt; &lt;link name="B" text="Login" href="SignIn.php" index="15"/&gt; &lt;link name="C" text="Login" href="Login.php" index="22"/&gt; &lt;/links&gt; </code></pre> <p><strong>the correct result is produced</strong>:</p> <pre><code>&lt;link name="C" text="Login" href="Login.php" index="22" /&gt; </code></pre> <p><strong>This reminds me of <a href="http://www.biglist.com/lists/xsl-list/archives/200207/msg00804.html" rel="nofollow noreferrer">another "Single XPath expression finding the best matches" problem</a></strong> <strong>I solved some seven year ago :)</strong></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload