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>
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>
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.