From 8216a6ef3d8d16f9de23389b0f6b489cbde074bd Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Sun, 13 Feb 2011 15:58:52 +0100 Subject: [PATCH] [Serializer] Added XmlEncoder::setRootNodeName --- .../Serializer/Encoder/XmlEncoder.php | 25 ++++++++++++++++--- .../Serializer/Encoder/XmlEncoderTest.php | 12 +++++++++ 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php b/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php index 68d7a0b510..24cf257105 100644 --- a/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php +++ b/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php @@ -24,6 +24,7 @@ class XmlEncoder extends AbstractEncoder { protected $dom; protected $format; + protected $rootNodeName = 'response'; /** * {@inheritdoc} @@ -38,11 +39,11 @@ class XmlEncoder extends AbstractEncoder $this->format = $format; if ($this->serializer->isStructuredType($data)) { - $root = $this->dom->createElement('response'); + $root = $this->dom->createElement($this->rootNodeName); $this->dom->appendChild($root); $this->buildXml($root, $data); } else { - $this->appendNode($this->dom, $data, 'response'); + $this->appendNode($this->dom, $data, $this->rootNodeName); } return $this->dom->saveXML(); } @@ -59,6 +60,24 @@ class XmlEncoder extends AbstractEncoder return $this->parseXml($xml); } + /** + * Sets the root node name + * @param string $name root node name + */ + public function setRootNodeName($name) + { + $this->rootNodeName = $name; + } + + /** + * Returns the root node name + * @return string + */ + public function getRootNodeName() + { + return $this->rootNodeName; + } + /** * Parse the input SimpleXmlElement into an array * @@ -120,7 +139,7 @@ class XmlEncoder extends AbstractEncoder if (!$parentNode->parentNode->parentNode) { $root = $parentNode->parentNode; $root->removeChild($parentNode); - return $this->appendNode($root, $data, 'response'); + return $this->appendNode($root, $data, $this->rootNodeName); } return $this->appendNode($parentNode, $data, 'data'); } diff --git a/tests/Symfony/Tests/Component/Serializer/Encoder/XmlEncoderTest.php b/tests/Symfony/Tests/Component/Serializer/Encoder/XmlEncoderTest.php index 0edf1e7cd9..73a0a8daef 100644 --- a/tests/Symfony/Tests/Component/Serializer/Encoder/XmlEncoderTest.php +++ b/tests/Symfony/Tests/Component/Serializer/Encoder/XmlEncoderTest.php @@ -41,6 +41,18 @@ class XmlEncoderTest extends \PHPUnit_Framework_TestCase $this->assertEquals($expected, $this->encoder->encode($obj, 'xml')); } + public function testSetRootNodeName() + { + $obj = new ScalarDummy; + $obj->xmlFoo = "foo"; + + $this->encoder->setRootNodeName('test'); + $expected = ''."\n". + ''."\n"; + + $this->assertEquals($expected, $this->encoder->encode($obj, 'xml')); + } + public function testEncodeSimpleXML() { $xml = simplexml_load_string('Peter');