6

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.

1 Answer 1

15

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.