简体   繁体   中英

How to change node name in XML using symfony serializer?

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;
    }
}

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);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM