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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With