Support to namespaces in Xml::toArray.

This commit is contained in:
Juan Basso 2010-07-28 19:46:35 -03:00
parent f4d5230dfa
commit b862d68016
2 changed files with 25 additions and 7 deletions

View file

@ -118,7 +118,8 @@ class Xml {
throw new Exception(__('The input is not instance of SimpleXMLElement.')); throw new Exception(__('The input is not instance of SimpleXMLElement.'));
} }
$result = array(); $result = array();
self::_toArray($simpleXML, $result); $namespaces = array_merge(array('' => ''), $simpleXML->getNamespaces(true));
self::_toArray($simpleXML, $result, array_keys($namespaces));
return $result; return $result;
} }
@ -127,17 +128,20 @@ class Xml {
* *
* @param object $xml SimpleXMLElement object * @param object $xml SimpleXMLElement object
* @param array $parentData Parent array with data * @param array $parentData Parent array with data
* @param array $namespaces List of namespaces in XML
* @return void * @return void
*/ */
protected static function _toArray($xml, &$parentData) { protected static function _toArray($xml, &$parentData, $namespaces) {
$data = array(); $data = array();
foreach ($xml->attributes() as $key => $value) { foreach ($namespaces as $namespace) {
foreach ($xml->attributes($namespace, true) as $key => $value) {
$data[$key] = (string)$value; $data[$key] = (string)$value;
} }
foreach ($xml->children() as $child) { foreach ($xml->children($namespace, true) as $child) {
self::_toArray($child, $data); self::_toArray($child, $data, $namespaces);
}
} }
$asString = trim((string)$xml); $asString = trim((string)$xml);

View file

@ -323,6 +323,20 @@ class XmlTest extends CakeTestCase {
) )
); );
$this->assertEqual(Xml::toArray($obj), $expected); $this->assertEqual(Xml::toArray($obj), $expected);
$xml = '<root xmlns:cake="http://www.cakephp.org/">';
$xml .= '<tag>defect</tag>';
$xml .= '<cake:bug>1</cake:bug>';
$xml .= '</root>';
$obj = Xml::build($xml);
$expected = array(
'root' => array(
'tag' => 'defect',
'bug' => 1
)
);
$this->assertEqual(Xml::toArray($obj), $expected);
} }
} }