MrRisoni
MrRisoni

Reputation: 53

Symfony Serializer XML Attribute

I want to use the Symfony XML Serializer to transform a class instance (not an array). So for example I want to create an XML like so with the attribute myAtt="foo" ,

<?xml version="1.0"?>
<REQ>
    <TravelAgencySender myAtt="foo">
        <CityName>town</CityName>
        <AgencyID>agency</AgencyID>
    </TravelAgencySender>   
</REQ>

So I have created a class like so

class TravelAgencySender 
{

    /**
     * @var string
     */
    private  $CityName;
    /**
     * @var string
     */
    public  $AgencyID;
.....
}

And the following initialization

use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\NameConverter\MetadataAwareNameConverter;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
use Doctrine\Common\Annotations\AnnotationReader;



$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));

$metadataAwareNameConverter = new MetadataAwareNameConverter($classMetadataFactory);

$serializer = new Serializer(
    [new ObjectNormalizer($classMetadataFactory, $metadataAwareNameConverter)],
    ['json' => new JsonEncoder(), 'xml' => new XmlEncoder()]
);

Does anyone know how to add the myAtt attribute?

Thanks

And this produces the below XML

<?xml version="1.0"?>
<REQ>
    <TravelAgencySender>
        <CityName>town</CityName>
        <AgencyID>agency</AgencyID>
    </TravelAgencySender>   
</REQ>

Upvotes: 2

Views: 1650

Answers (2)

Isidro Moran
Isidro Moran

Reputation: 330

You have to use SerializedName as follows:

use Symfony\Component\Serializer\Annotation\SerializedName;
    
class TravelAgencySender 
    {
        /**
         * @SerializedName("@myAtt")
         * @var string
         */
        private  $foo;
        /**
         * @var string
        */
        private  $CityName;
        /**
         * @var string
         */
        public  $AgencyID;
    .....
    }

Upvotes: 1

Michele
Michele

Reputation: 270

The array keys beginning with @ are considered XML attributes:

['foo' => ['@bar' => 'value']];

is encoded as follows:

<?xml version="1.0"?>
<response>
     <foo bar="value"/>
</response>

Upvotes: 0

Related Questions