PHP Xpath返回零匹配

时间:2016-10-18 13:22:50

标签: php xpath

考虑这个XML

<?xml version="1.0" encoding="UTF-8"?> <Assertion xmlns="urn:oasis:names:tc:SAML:2.0:assertion" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:oasis:names:tc:SAML:2.0:assertion http://docs.oasis-open.org/security/saml/v2.0/saml-schema-assertion-2.0.xsd" ID="_a75adf55-01d7-40cc-929f-dbd8372ebdfc" IssueInstant="2009-09-09T00:46:02Z" Version="2.0"> <Subject> <NameID>801234567890</NameID> </Subject> .... </Assertion>

PHP

$dom = new DOMDocument(); $ret = $dom->loadXML($data); $xp = new DOMXPath($dom); $node_list = $xp->query('/Assertion');

$node_list->length返回0个元素。我想提取DOMElement但不知何故它不起作用。

1 个答案:

答案 0 :(得分:1)

正如Sami Kuhmonen的评论所述,您可能需要注册名称空间,这是一个例子:

<?php
$string= <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<Assertion xmlns="urn:oasis:names:tc:SAML:2.0:assertion" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:oasis:names:tc:SAML:2.0:assertion http://docs.oasis-open.org/security/saml/v2.0/saml-schema-assertion-2.0.xsd" ID="_a75adf55-01d7-40cc-929f-dbd8372ebdfc" IssueInstant="2009-09-09T00:46:02Z" Version="2.0">
   <Subject>
      <NameID>801234567890</NameID>
   </Subject>
</Assertion>
XML;

$dom = new DOMDocument();
$dom->loadXML($string);
$xp = new DOMXPath($dom);

// registering the namespaces
$xp->registerNamespace('a','urn:oasis:names:tc:SAML:2.0:assertion');
$xp->registerNamespace('b','http://www.w3.org/2001/XMLSchema-instance');

// using the prefix of the registered namespace in the xpath expression
$node_list = $xp->query('/a:Assertion');

print $node_list->length
?>