I have an XML document with items book
with attributes .id
, for example .id 'bk100', 'bk102', 'bk105', 'bk112', 'bk130'
. I want to create an xpath that will return only those items which satisfy this condition:
我有一个带有属性id的XML文档,例如。id 'bk100', 'bk102', 'bk105', 'bk112', 'bk130'。我想创建一个xpath,它只返回满足此条件的项:
.id > 'bk104'
That should return items with the .id 'bk105', 'bk112', 'bk130'
. I have this:
这将返回带有.id 'bk105'、'bk112'、'bk130'的项。我有这个:
xpath("//book[@id>'bk112']");
But it doesn't seem to do the trick. Is there any modifier to make this happen, or do I have to implement this manually?
但这似乎并没有起到什么作用。是否有修改器来实现这一点,还是我必须手动实现它?
2 个解决方案
#1
3
The compare function was added in XPath 2, which sadly isn't available.
比较函数是在XPath 2中添加的,遗憾的是它不可用。
With the DOM extension you can register PHP functions for use in XPath expressions and strcmp does the trick there.
使用DOM扩展,您可以注册PHP函数,以便在XPath表达式中使用,strcmp可以实现这一点。
Example:
$xml = <<<'XML'
<books>
<book id="bk100"/>
<book id="bk102"/>
<book id="bk105"/>
<book id="bk112"/>
<book id="bk130"/>
</books>
XML;
$dom = new DOMDocument();
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);
$xpath->registerPhpFunctions('strcmp');
$xpath->registerNamespace("php", "http://php.net/xpath");
foreach ($xpath->query("//book[php:functionString('strcmp', @id, 'bk104') > 0]") as $node) {
echo $dom->saveXML($node), "\n";
}
Output:
<book id="bk105"/>
<book id="bk112"/>
<book id="bk130"/>
Otherwise you'll need to implement it manually.
否则,您将需要手动实现它。
#2
1
If you you have constant id prefix
如果你有常数id前缀
bk
汉堡王
you can mitigate this problem by using standard xpath function substring (extract number from id) and number (convert string to number) as below:
您可以通过使用标准的xpath函数子字符串(从id中提取数字)和数字(将字符串转换为数字)来缓解这个问题,如下所示:
xpath('//book[number(substring(@id, 3))>104]'))
#1
3
The compare function was added in XPath 2, which sadly isn't available.
比较函数是在XPath 2中添加的,遗憾的是它不可用。
With the DOM extension you can register PHP functions for use in XPath expressions and strcmp does the trick there.
使用DOM扩展,您可以注册PHP函数,以便在XPath表达式中使用,strcmp可以实现这一点。
Example:
$xml = <<<'XML'
<books>
<book id="bk100"/>
<book id="bk102"/>
<book id="bk105"/>
<book id="bk112"/>
<book id="bk130"/>
</books>
XML;
$dom = new DOMDocument();
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);
$xpath->registerPhpFunctions('strcmp');
$xpath->registerNamespace("php", "http://php.net/xpath");
foreach ($xpath->query("//book[php:functionString('strcmp', @id, 'bk104') > 0]") as $node) {
echo $dom->saveXML($node), "\n";
}
Output:
<book id="bk105"/>
<book id="bk112"/>
<book id="bk130"/>
Otherwise you'll need to implement it manually.
否则,您将需要手动实现它。
#2
1
If you you have constant id prefix
如果你有常数id前缀
bk
汉堡王
you can mitigate this problem by using standard xpath function substring (extract number from id) and number (convert string to number) as below:
您可以通过使用标准的xpath函数子字符串(从id中提取数字)和数字(将字符串转换为数字)来缓解这个问题,如下所示:
xpath('//book[number(substring(@id, 3))>104]'))