2

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>
1
  • 1
    Move on to JMSSerializer Bundle if you can. An example with attribute is here. Commented Apr 19, 2019 at 21:31

2 Answers 2

1

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;
    .....
    }
Sign up to request clarification or add additional context in comments.

1 Comment

How do you do this via Annotations or PHP Attributes on the root node though?
0

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>

1 Comment

Is not an array. Is an object. Your comment doesn't make any sense.

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.