Search code examples
phpxmlsimplexml

XML Obtaining Namespaced node values


I have this xml fragment:

<ModelList>
               <ProductModel>
                  <CategoryCode>06</CategoryCode>
                  <Definition>
                     <ListProperties xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
                        <a:KeyValueOfstringArrayOfstringty7Ep6D1>
                           <a:Key>Couleur principale</a:Key>
                           <a:Value>
                              <a:string>Blanc</a:string>
                              <a:string>Noir</a:string>
                              <a:string>Gris</a:string>
                              <a:string>Inox</a:string>
                              <a:string>Rose</a:string>

That I am attempting to parse (with simplexml) with this:

$xml->registerXPathNamespace('a', 'http://schemas.microsoft.com/2003/10/Serialization/Arrays');

        $x = $xml->xpath('//a:KeyValueOfstringArrayOfstringty7Ep6D1');
        //var_dump($x);


        foreach($x as $k => $model) {
            $key = (string)$model->Key;
            var_dump($model->Key);
        }

That var dump currently returns a whole bunch of

object(SimpleXMLElement)[7823]

Which appears to contain the a:Value block. So how do I get the value of the node, not the blasted object tree?

And people think xml is easily parsed.


Solution

  • Sounds like you problem is more with SimpleXML as with XML itself. You might want to try DOM.

    You can casts results in XPath itself, so the expression will return a scalar value directly.

    $dom = new DOMDocument();
    $dom->loadXml($xml);
    $xpath = new DOMXPath($dom);
    $xpath->registerNamespace('a', 'http://schemas.microsoft.com/2003/10/Serialization/Arrays');
    
    $items = $xpath->evaluate('//a:KeyValueOfstringArrayOfstringty7Ep6D1');
    
    foreach ($items as $item) {
      $key = $xpath->evaluate('string(a:Key)', $item);
      var_dump($key);
    }
    

    Output:

    string(18) "Couleur principale"