考虑以下XML:
<?xml version="1.0" encoding="utf-8"?>
<movies xmlns:en="http://english-language.com/">
<en:movie>
<title>The Godfather</title>
</en:movie>
<en:movie>
<title>Saving Private Ryan</title>
</en:movie>
<something-something xmlns:en="http://english.com/">
<en:movie>
<title>The Fellowship of the Ring</title>
</en:movie>
</something-something>
</movies>
下面的代码与“教父”和“拯救大兵瑞恩”匹配。但为什么?我希望它会失败。似乎查询会忽略名称空间名称(URI),而使用名称空间前缀
$xpath = new DOMXpath($dom);
$xpath->registerNamespace('en', 'http://complete-nonsense');
$elements = $xpath->query("//en:movie");
我希望下面的代码与《指环王》相匹配,但还是与《教父》和《拯救大兵瑞恩》相匹配。
$xpath = new DOMXpath($dom);
$xpath->registerNamespace('en', 'http://english.com/');
$elements = $xpath->query("//en:movie");
只是现在URI似乎没有什么不同,现在它与The Fellowship of the Ring匹配。
$xpath = new DOMXpath($dom);
$xpath->registerNamespace('english', 'http://english.com/');
$elements = $xpath->query("//english:movie");
这是为什么?PHP的实现有问题吗?
DOMXpath::evaluate()
/DOMXpath::query()
在手动注册的上下文节点顶部注册当前上下文节点的名称空间定义。基本上,文档将覆盖名称空间作为前缀。第三个参数(因为PHP> = 5.3.3)可以禁用自动注册:
$document = new DOMDocument();
$document->loadXML($xml);
$xpath = new DOMXpath($document);
$xpath->registerNamespace('en', 'http://english.com/');
// the xmlns:en from the document element overrides the registration
var_dump($xpath->evaluate('normalize-space(//en:movie)'));
// automatic registration disabled - works correctly
var_dump($xpath->evaluate('normalize-space(//en:movie)', NULL, FALSE));
输出:
string(13) "The Godfather"
string(26) "The Fellowship of the Ring"
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句