Skip to content

Commit

Permalink
feature #20524 [Serializer][XmlEncoder] Allow removing empty tags in …
Browse files Browse the repository at this point in the history
…generated XML (amoiraud)

This PR was squashed before being merged into the 3.3-dev branch (closes #20524).

Discussion
----------

[Serializer][XmlEncoder] Allow removing empty tags in generated XML

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | #20398
| License       | MIT
| Doc PR        | ~

Allow a new option in $context of XmlEncoder.php to remove empty tags if $context['remove_empty_tags'] setted to true, changing this :

```xml
    <node>
         <subnode>Value</subnode>
         <emptysubnode/>
    </node>
```

To this :

```xml
    <node>
         <subnode>Value</subnode>
    </node>
```

Commits
-------

0cb4d8e [Serializer][XmlEncoder] Allow removing empty tags in generated XML
  • Loading branch information
dunglas committed Dec 6, 2016
2 parents 24d8135 + 0cb4d8e commit 4644ee9
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Symfony/Component/Serializer/Encoder/XmlEncoder.php
Expand Up @@ -392,7 +392,7 @@ private function buildXml(\DOMNode $parentNode, $data, $xmlRootNodeName = null)
}
} elseif (is_numeric($key) || !$this->isElementNameValid($key)) {
$append = $this->appendNode($parentNode, $data, 'item', $key);
} else {
} elseif (null !== $data || !isset($this->context['remove_empty_tags']) || false === $this->context['remove_empty_tags']) {
$append = $this->appendNode($parentNode, $data, $key);
}
}
Expand Down
22 changes: 22 additions & 0 deletions src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php
Expand Up @@ -138,6 +138,28 @@ public function testEncodeXmlAttributes()
$this->assertSame($expected, $this->encoder->encode($array, 'xml', $context));
}

public function testEncodeRemovingEmptyTags()
{
$array = array('person' => array('firstname' => 'Peter', 'lastname' => null));

$expected = '<?xml version="1.0"?>'."\n".
'<response><person><firstname>Peter</firstname></person></response>'."\n";

$context = array('remove_empty_tags' => true);

$this->assertSame($expected, $this->encoder->encode($array, 'xml', $context));
}

public function testEncodeNotRemovingEmptyTags()
{
$array = array('person' => array('firstname' => 'Peter', 'lastname' => null));

$expected = '<?xml version="1.0"?>'."\n".
'<response><person><firstname>Peter</firstname><lastname/></person></response>'."\n";

$this->assertSame($expected, $this->encoder->encode($array, 'xml'));
}

public function testContext()
{
$array = array('person' => array('name' => 'George Abitbol'));
Expand Down

0 comments on commit 4644ee9

Please sign in to comment.