【问题标题】:Using xpath on a PHP SimpleXML object, SOAP + namespaces (not working..)在 PHP SimpleXML 对象上使用 xpath,SOAP + 命名空间(不起作用..)
【发布时间】:2010-10-05 14:01:58
【问题描述】:

在 SO 和谷歌上研究了几个小时之后......我希望在这里得到一些帮助: (我距离运行正则表达式以完全删除命名空间仅一步之遥)

首先这是 XML:

<?xml version="1.0" encoding="utf-16"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header xmlns="http://webservices.site.com/definitions">
    <SessionId>0119A|1</SessionId>
  </soap:Header>
  <soap:Body>
    <Security_AuthenticateReply xmlns="http://xml.site.com/QQ">
      <processStatus>
        <statusCode>P</statusCode>
      </processStatus>
    </Security_AuthenticateReply>
  </soap:Body>
</soap:Envelope>

这就是我在 PHP 中的代码的样子:

$response = simplexml_load_string( $str ,NULL, 
false, "http://schemas.xmlsoap.org/soap/envelope/" );
// just making sure the name space is "registered"
// but I tested all examples also with this removed
$response->registerXPathNamespace("soap",
    "http://schemas.xmlsoap.org/soap/envelope/");
$_res = $response->xpath('//soap:Header');
print_r($_res);
/*** result: simple query for the root "soap" namespace, this looks good! (so far..)
Array
(
    [0] => SimpleXMLElement Object
        (
            [SessionId] => 0119A|1
        )

)
***/

// now we query for the "SessionId" element in the XML
$_res = $response->xpath('//soap:Header/SessionId');
print_r($_res);
/*** result: this does not return anything!
Array
(
)
***/

// another approach
$_res = $response->xpath('//soap:Header/SessionId/text()');
print_r($_res);
/*** result: this does not return anything at all!
***/

// Finally, without using XPath this does work
$_res = $response->xpath('//soap:Header');
$_res = (string)$_res[0]->SessionId;
echo $_res;
/*** result: this worked
0119A|1
***/

如何让 SOAP 消息与 XPATH 一起使用???

谢谢, 罗马

【问题讨论】:

  • 最简单的方法是使用 DOM 而不是 SimpleXml,但我想这不是一个选项?
  • 我发现当我更改这部分 XML 时:
    webservices.site.com/definitions"> To:
    上述 Xpath 查询开始工作.. 任何想法对此? XML 格式错误??

标签: php soap xpath simplexml


【解决方案1】:

多个命名空间搞砸了,为我添加以下作品

$response->registerXPathNamespace("site", "http://webservices.site.com/definitions");
$_res = $response->xpath('//site:SessionId');

另外,请参阅this 上一个堆栈溢出问题

【讨论】:

  • 两个答案都很好,因为你的速度更快(一分钟),我选择它作为正确答案:)
【解决方案2】:

您还需要注册&lt;SessionId&gt; 元素使用的默认命名空间。因为&lt;SessionId&gt; 在默认命名空间中,它没有任何前缀,但为了让您的 XPath 工作,您还需要将此命名空间绑定到某个前缀,然后在 XPath 表达式中使用该前缀。

$response->registerXPathNamespace("ns",
    "http://webservices.site.com/definitions");
$_res = $response->xpath('//soap:Header/ns:SessionId');

没有命名空间前缀的 XPath (1.0) 表达式始终只匹配无命名空间中的目标。

【讨论】:

    猜你喜欢
    • 2015-10-13
    • 2018-07-05
    • 2012-01-06
    • 1970-01-01
    • 2014-06-20
    • 2013-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多