Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 21 additions & 12 deletions src/Symfony/Component/Serializer/Encoder/XmlEncoder.php
Original file line number Diff line number Diff line change
Expand Up @@ -140,26 +140,22 @@ public function decode(string $data, string $format, array $context = [])
// todo: throw an exception if the root node name is not correctly configured (bc)

if ($rootNode->hasChildNodes()) {
$xpath = new \DOMXPath($dom);
$data = [];
foreach ($xpath->query('namespace::*', $dom->documentElement) as $nsNode) {
$data['@'.$nsNode->nodeName] = $nsNode->nodeValue;
$data = $this->parseXml($rootNode, $context);
if (\is_array($data)) {
$data = $this->addXmlNamespaces($data, $rootNode, $dom);
}

unset($data['@xmlns:xml']);

if (empty($data)) {
return $this->parseXml($rootNode, $context);
}

return array_merge($data, (array) $this->parseXml($rootNode, $context));
return $data;
}

if (!$rootNode->hasAttributes()) {
return $rootNode->nodeValue;
}

return array_merge($this->parseXmlAttributes($rootNode, $context), ['#' => $rootNode->nodeValue]);
$data = array_merge($this->parseXmlAttributes($rootNode, $context), ['#' => $rootNode->nodeValue]);
$data = $this->addXmlNamespaces($data, $rootNode, $dom);

return $data;
}

/**
Expand Down Expand Up @@ -344,6 +340,19 @@ private function parseXmlValue(\DOMNode $node, array $context = [])
return $value;
}

private function addXmlNamespaces(array $data, \DOMNode $node, \DOMDocument $document): array
{
$xpath = new \DOMXPath($document);

foreach ($xpath->query('namespace::*', $node) as $nsNode) {
$data['@'.$nsNode->nodeName] = $nsNode->nodeValue;
}

unset($data['@xmlns:xml']);

return $data;
}

/**
* Parse the data and convert it to DOMElements.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,17 @@ public function testDecodeWithNamespace()
$array = $this->getNamespacedArray();

$this->assertEquals($array, $this->encoder->decode($source, 'xml'));

$source = '<?xml version="1.0"?>'."\n".
'<response xmlns="http://www.w3.org/2005/Atom" xmlns:app="http://www.w3.org/2007/app" app:foo="bar">'.
'</response>'."\n";

$this->assertEquals([
'@xmlns' => 'http://www.w3.org/2005/Atom',
'@xmlns:app' => 'http://www.w3.org/2007/app',
'@app:foo' => 'bar',
'#' => '',
], $this->encoder->decode($source, 'xml'));
}

public function testDecodeScalarWithAttribute()
Expand Down