我想使用Symfony XML序列化器转换类实例(而不是数组)。因此,例如,我想使用属性myAtt =“ foo”创建这样的XML,
<?xml version="1.0"?>
<REQ>
<TravelAgencySender myAtt="foo">
<CityName>town</CityName>
<AgencyID>agency</AgencyID>
</TravelAgencySender>
</REQ>
所以我创建了一个像这样的类
class TravelAgencySender
{
/**
* @var string
*/
private $CityName;
/**
* @var string
*/
public $AgencyID;
.....
}
以及以下初始化
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()]
);
有人知道如何添加myAtt属性吗?
谢谢
这将产生以下XML
<?xml version="1.0"?>
<REQ>
<TravelAgencySender>
<CityName>town</CityName>
<AgencyID>agency</AgencyID>
</TravelAgencySender>
</REQ>
答案 0 :(得分:0)
以@开头的数组键被视为XML属性:
['foo' => ['@bar' => 'value']];
编码如下:
<?xml version="1.0"?>
<response>
<foo bar="value"/>
</response>