0

How to change the node name of XML document generated by Symfony serializer? I generate XML with this code:

final class AdsController extends AbstractController
{
    private SerializerInterface $serializer;

    public function __construct(SerializerInterface $serializer)
    {
        $this->serializer = $serializer;
        $this->normalizer = $normalizer;
    }

    public function __invoke(Request $request): Response
    {
        $ads = $this->em->findAll();
        $rootNode = [
            '@id' => 12345,
            '#' => $ads
        ];
        $res = $this->serializer->serialize($rootNode, 'xml', [
            'xml_format_output' => true,
            'xml_encoding' => 'utf-8',
            'xml_root_node_name' => 'ads'
]);

        return $res;
    }
}

And the $res looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<ads id="12345">
    <item></item>
</ads>

But how to get something like this:

<?xml version="1.0" encoding="UTF-8"?>
<ads id="12345">
    <ad adId="123"></ad>
</ads>

My normalizer looks like this:

class AdNormalizer implements ContextAwareNormalizerInterface
{
    public function normalize($topic, string $format = null, array $context = [])
    {
        $data['adName'] = ...
        return $data;
    }

    public function supportsNormalization($data, string $format = null, array $context = [])
    {
        return $data instanceof Ad;
    }
}

1 Answer 1

2

I'm not sure about details in the context of vanilla Symfony, but here is how I do in Drupal using Symfony\Component\Serializer\Encoder\XmlEncoder

  public function encode() {
    $list = [
      [
        '@id' => '123',
        'propertyOne' => 1,
        'propertyTwo' => 2,
      ],
      [
        '@id' => '456',
        'propertyOne' => 1,
        'propertyTwo' => 2,
      ],
      [
        '@id' => '789',
        'propertyOne' => 1,
        'propertyTwo' => 2,
      ]
    ];
    // The root element name defined via:
    $context[XmlEncoder::ROOT_NODE_NAME] = 'ads';
    $list = ['ad' => $list];
    
    $ads = [
      '@id' => 12345,
      '#' => $list
    ];

    $encoder = new \Symfony\Component\Serializer\Encoder\XmlEncoder();
    return $encoder->encode($ads, $format, $context);
  }
Sign up to request clarification or add additional context in comments.

1 Comment

thank you very much it works and this is what I was looking for

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.