xpath expression for numeric comparison
I'm writing a Greasemonkey script so can't change the source XHTML.
Given the following XHTML fragment:
<td>
<span class="entry">Gender, Age:</span> Female, 42<br>
<span class="entry">Country, Town:</span> United Kingdom, London
<span class="small09"></span>
</td>
is it possible to write an expression that can be evaluated using document.evaluate that will allow me to select all entries where the age is greater than, say, 40? I want something such as the following:
var matches = document.evaluate("//table[tbody/tr[2]/td[1][number(SOMEHOW
MA开发者_运维问答TCH THE AGE PART) > 40]]",
document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
null);
Thanks
Use:
//table[tbody/tr[2]/td[1]
[number(
substring-after(normalize-space(span[1]/following-sibling::text()[1]),
',')
)
>
40
]
]
You can't use conditionals on text content, but you can filter the results with JavaScript.
Something like this should work:
var targetCells = document.evaluate (
"//table/tbody/tr[2]/td[1]",
document,
null,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
null
);
for (var J = targetCells.snapshotLength - 1; J >= 0; --J)
{
var thisCell = targetCells.snapshotItem (J);
//--- Get the age. Key off (fe)male, {age in decimal years}<br> in the text of the table cell
var ageTxt = thisCell.textContent.match (/male[, ]+(\d+)/i);
if (ageTxt && ageTxt.length > 1)
{
var age = parseInt (ageTxt[1]);
if (age > 40)
{
//-----------------------
//--- DO YOUR STUFF HERE.
//-----------------------
}
}
}
If you set age as an attribute you can access that value.
Something like
<Person Gender="F" Age="42" />
精彩评论