steelpush
steelpush

Reputation: 109

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.

Upvotes: 2

Views: 114

Answers (2)

steelpush
steelpush

Reputation: 109

So I have eventually resolved this problem. For reference (after much trial and error, including a solution based on ThW's answer), this code gets the key property correctly:

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

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


        foreach($x as $k => $model) {

            var_dump((string)$model);
        } 

Upvotes: 1

ThW
ThW

Reputation: 19502

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"

Upvotes: 1

Related Questions