首页 > 解决方案 > simplexml_load_string asXML 不为空,但 children() 函数返回空?

问题描述

echo $xml->asXML();

打印以下内容,我正在尝试访问此处的元素,例如:InvoiceStateResult

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
    xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing"
    xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
    xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
    <soap:Header>
        <wsa:Action>http://tempuri.org/SendEArchiveDataResponse</wsa:Action>
        <wsa:MessageID>urn:uuid:72e8aaf0-b36d-422f-ab0b-486c17c50c83</wsa:MessageID>
        <wsa:RelatesTo>urn:uuid:fc0a3e9d-40c1-4f3b-9517-8002825b7217</wsa:RelatesTo>
        <wsa:To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To>
        <wsse:Security>
            <wsu:Timestamp wsu:Id="Timestamp-3a82271a-a910-4062-81aa-984468387047">
                <wsu:Created>2021-05-28T12:12:23Z</wsu:Created>
                <wsu:Expires>2021-05-28T12:27:23Z</wsu:Expires>
            </wsu:Timestamp>
        </wsse:Security>
    </soap:Header>
    <soap:Body>
        <SendEArchiveDataResponse
            xmlns="http://tempuri.org/">
            <SendEArchiveDataResult>
                <Invoices>
                    <InvoiceStateResult>
                        <ServiceResult>Error</ServiceResult>
                        <UUID>11111111-2222-3333-4444-555555555555</UUID>
                        <InvoiceId>T612014000000053</InvoiceId>
                        <StatusDescription>INVOICE EXISTS</StatusDescription>
                        <StatusCode>29</StatusCode>
                        <ErrorCode>0</ErrorCode>
                        <ReferenceNo>T612014000000053</ReferenceNo>
                    </InvoiceStateResult>
                </Invoices>
                <ServiceResult>Error</ServiceResult>
                <ServiceResultDescription>This invoice processed before InvoiceId : TRL2021000000019 , UUID : DB3642EB-7A5F-40FD-8DF8-A922CA113837 SenderTaxID : 3324502175 . </ServiceResultDescription>
                <Source>IntegrationWebService</Source>
                <ErrorCode>30</ErrorCode>
                <invoiceCount>1</invoiceCount>
            </SendEArchiveDataResult>
        </SendEArchiveDataResponse>
    </soap:Body>
</soap:Envelope>

但是我无法到达任何节点。我试过这个:

foreach($xml->children() as $child) {
    echo "Child node: " . $child . "</br>";
}

它返回空。

我将如何访问节点?

谢谢

标签: phpxmlsimplexml

解决方案


简单 XML,顾名思义,是一个非常简单的实现,它查找标准名称空间。您可以使用 registerXPathNamespace 来查找非自定义的。请参阅下面适用于您的代码的示例。

$xml = simplexml_load_string($string);
$xml->registerXPathNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
print_r($xml->xpath('//soap:Body')[0]->SendEArchiveDataResponse->SendEArchiveDataResult->Invoices->InvoiceStateResult);

推荐阅读