Akshay
Akshay

Reputation: 2229

Accessing XML data within namespaces

So my XML Looks like this :-

<ns0:ASN xmlns:ns0="http://schemas.microsoft.com/dynamics/2008/01/documents/ASN" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <ns0:CustPackingSlipJour class="entity">
   <ns0:BON_FileNameSeqNum>40</ns0:BON_FileNameSeqNum>
   <ns0:BON_TotalNetAmount>10.00</ns0:BON_TotalNetAmount>
   <ns0:BON_TotalTaxAmount>.00</ns0:BON_TotalTaxAmount>
   <ns0:InvoiceAccount>Acc</ns0:InvoiceAccount>
   <ns0:LanguageId>EN</ns0:LanguageId>
   <ns0:OrderAccount>I</ns0:OrderAccount>
   <ns0:PurchaseOrder>74</ns0:PurchaseOrder>
   <ns0:Qty>13.00</ns0:Qty>
   <ns0:SalesId>00025873_054</ns0:SalesId>
   <ns0:CustPackingSlipTrans class="entity">
    <ns0:BON_LineNetAmount>19.00</ns0:BON_LineNetAmount>
    <ns0:BON_SalesPrice>0.00</ns0:BON_SalesPrice>
    <ns0:DeliveryDate>2016-11-30</ns0:DeliveryDate>
    <ns0:ItemId>25712</ns0:ItemId>
    <ns0:Ordered>1.00</ns0:Ordered>
    <ns0:PackingSlipId>00339_061</ns0:PackingSlipId>
    <ns0:Qty>1.00</ns0:Qty>
   </ns0:CustPackingSlipTrans>
   <ns0:CustPackingSlipTrans class="entity">
    <ns0:BON_LineNetAmount>19.00</ns0:BON_LineNetAmount>
    <ns0:BON_SalesPrice>0.00</ns0:BON_SalesPrice>
    <ns0:DeliveryDate>2-11-30</ns0:DeliveryDate>
    <ns0:ItemId>25823-35714</ns0:ItemId>
    <ns0:Ordered>1.00</ns0:Ordered>
    <ns0:PackingSlipId>00_061</ns0:PackingSlipId>
    <ns0:Qty>1.00</ns0:Qty>
   </ns0:CustPackingSlipTrans>
  </ns0:CustPackingSlipJour>
 </ns0:ASN>

How can I access the value of ItemId for all CustPackingSlipTrans ?

I have tried various ways of getting it, for instance registering xpath and then trying to access. However, it ins't working for me. Whats the best way to get it's value?

Upvotes: 1

Views: 27

Answers (2)

Mike
Mike

Reputation: 2761

You need to register the namespace with the DomXPath:

    $xp = new DomXPath ($doc);
    $xp->registerNamespace ('pfx', 'http://pfxuri');

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

The solution using DOMXPath::query method:

// $xml contains your xml contents
$doc = new \DOMDocument();
$doc->loadXML($xml);
$xpath = new \DOMXPath($doc);

foreach ($xpath->query("ns0:CustPackingSlipJour/ns0:CustPackingSlipTrans/ns0:ItemId") as $node) {
    var_dump($node->nodeValue);
}

The output:

string(5) "25712"
string(11) "25823-35714"

DEMO

Upvotes: 1

Related Questions