XPath 1.0获取最低出价遇序问题及次低价获取咨询
Why Your XPath Fails When Node Order Changes
Let's start with the root cause here: XPath 1.0 treats node sets as single strings in functions expecting text values by only using the first node's content.
In your original expression:
//current_bid[not(translate (., '$,.','') > translate(//current_bid, '$,.',''))]
When you pass //current_bid to the second translate() call, XPath 1.0 doesn't process all nodes—it grabs the first <current_bid> in the document and converts only that to a numeric string.
- In your first dataset, the first node is
$1.00, sotranslate(//current_bid, '$,.','')returns100. Every other node's translated value is greater than100, sonot(...)only returnstruefor the first node. - In your second dataset, the first node is
$5.00, sotranslate(//current_bid, '$,.','')returns500. All other nodes' translated values are less than500, sonot(...)returnstruefor every node—hence your bug.
To fix this, you need to compare each node to all other nodes explicitly, not just the first one. A correct XPath 1.0 expression for the lowest bid is:
//current_bid[not(//current_bid[translate(., '$,.','') < translate(current(), '$,.','')])]
This checks: "Is there no other <current_bid> whose numeric value is smaller than mine?" The current() function refers to the outer <current_bid> node being evaluated, so it works regardless of node order.
How to Get the Second Lowest Bid
To find the second lowest, we can build on the lowest bid logic: first exclude the lowest bids, then find the lowest value among the remaining nodes. Here's the XPath 1.0 expression:
//current_bid[ translate(., '$,.','') > translate(//current_bid[not(//current_bid[translate(., '$,.','') < translate(current(), '$,.','')])], '$,.','') ][ not(//current_bid[ translate(., '$,.','') > translate(current(), '$,.','') and translate(., '$,.','') < translate(current(), '$,.','') ]) ]
Let's break this down:
- The first condition filters out all nodes equal to the lowest bid (we only keep nodes with a higher value).
- The second condition then finds the lowest value among those remaining nodes (by checking there's no other node that's smaller than it but still larger than the original lowest).
For your second dataset ($5.00, $1.00, $2.00, $3.00, $4.00), this will correctly return $2.00.
内容的提问来源于stack exchange,提问作者Aydo

