使用JMS Serializer序列化为XML而不格式化(选项卡)

时间:2018-02-15 13:11:56

标签: php xml serialization jms-serializer

我正在使用xsd2php库(它本身使用jsm-serializer)。当我序列化对象时,它返回格式化的XML,例如:

<?xml version="1.0" encoding="UTF-8"?>
<priceRequest>
  <appId>PC</appId>
  <appVersion>3.0</appVersion>
</priceRequest>

如何调整序列化程序以输出XML而不进行格式化,如下所示:

<?xml version="1.0" encoding="UTF-8"?><priceRequest><appId>PC</appId><appVersion>3.0</appVersion></priceRequest>

现在我构建如下的序列化程序:

$serializerBuilder = SerializerBuilder::create();

$serializerBuilder->configureHandlers(function (HandlerRegistryInterface $handler) use ($serializerBuilder) {
    $serializerBuilder->addDefaultHandlers();
    $handler->registerSubscribingHandler(new BaseTypesHandler());
    $handler->registerSubscribingHandler(new XmlSchemaDateHandler());
    $handler->registerSubscribingHandler(new AnyTypeHandler());
});

$this->serializer = $serializerBuilder->build();

然后简单地序列化数据:

$this->serializer->serialize($data, $format, $context);

提前谢谢。

1 个答案:

答案 0 :(得分:0)

过了一会儿,我找到了解决方案,不确定它是否正确,但它确实有效。

XmlSerializationVisitor有公开方法setFormatOutput$formatOutput默认为true

SerializerBuilder默认设置访问者,因此默认XML序列化访问者访问者的$formatOutput也默认为true

我们可以使用setSerializationVisitor设置我们自己的序列化访问者。有趣的是,如果我们使用这种方法,则不会设置其他默认访问者(包括反序列化访问者)。因此,如果您必须设置一个非默认值,则必须设置所有。

请记住,我们可以配置我们的序列化程序进行XML序列化和反序列化,如下所示:

use JMS\Serializer\SerializerBuilder;
use JMS\Serializer\Naming\CamelCaseNamingStrategy;
use JMS\Serializer\Naming\SerializedNameAnnotationStrategy;
use JMS\Serializer\Accessor\DefaultAccessorStrategy;
use JMS\Serializer\XmlSerializationVisitor;
use JMS\Serializer\XmlDeserializationVisitor;

$serializerBuilder = SerializerBuilder::create();

$propertyNamingStrategy = new SerializedNameAnnotationStrategy(new CamelCaseNamingStrategy());
$accessorStrategy = new DefaultAccessorStrategy();
$serializationVisitor = new XmlSerializationVisitor($propertyNamingStrategy, $accessorStrategy);
$serializationVisitor->setFormatOutput(false); // <= So this is what all the fuss is about.
$deserializationVisitor = new XmlDeserializationVisitor($propertyNamingStrategy);

$serializerBuilder->setSerializationVisitor('xml', $serializationVisitor);
$serializerBuilder->setDeserializationVisitor('xml', $deserializationVisitor);

$this->serializer = $serializerBuilder->build();