douxing2156 2016-10-18 13:22
浏览 62
已采纳

PHP Xpath返回零匹配

Considering this 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 return 0 element. I want to extract the DOMElement but somehow it didn't work.

  • 写回答

1条回答 默认 最新

  • dongyan8929 2016-10-19 13:27
    关注

    As stated on the comments by Sami Kuhmonen you may need to register the namespaces, here is an example:

    <?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
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?