Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony Serializer XML add custom attribute to root node

When generating an XML file with Serializer component (in Symfony4) I want to add a custom attribute to the root node but I can't figure out how to.

The docs mention how to name the root node, but not how to add custom attributes.

In my service I have:

use Symfony\Component\Serializer\Serializer;
// ..

// $this->serializer is auto-wired
$this->serializer->serialize($myEntityObjectToSerialize, 'xml', [
  'xml_format_output' => true,
  'xml_encoding' => 'utf-8',
  'xml_root_node_name' => 'document'
]);

This generates:

<?xml version="1.0" encoding="utf-8"?>
<document>
// ...
</document>

But I want something like this:

<?xml version="1.0" encoding="utf-8"?>
<document id="123" lang="Eng">
// ...
</document>

I don't know what I'm missing. Thank you for the help.

like image 728
Miguel Avatar asked Mar 02 '23 11:03

Miguel


1 Answers

Ok, I figured it out.

Reading more about the XmlEncoder I saw that in order to add attributes to a node you use the @ symbol and the # for the value.

Since the serialize() creates the root node automatically and wraps it around my entity's data, I just needed to define it first, along with my entity, and then pass it to the serialize method like so:

$rootNode = [
  '@id' => 12345,
  '@lang' => 'Eng',
  '#' => $myEntityObjectToSerialize
]

// $this->serializer is auto-wired
$this->serializer->serialize($rootNode, 'xml', [
  'xml_format_output' => true,
  'xml_encoding' => 'utf-8',
  'xml_root_node_name' => 'document'
]);

And now it produces the result I was after. Hope this helps anyone in the future.

like image 153
Miguel Avatar answered Mar 07 '23 19:03

Miguel