我使用Symfony 3序列化器,并通过XmlEncoder将对象转换为XML。但是XmlEncoder在xml prolog中没有编码类型。如何解决这个问题呢?
是否可以在根元素之后添加带有参数的自定义属性?
有什么办法在根元素中设置xmlns吗?
我需要这样的XML输出:
<?xml version="1.0" encoding="utf-8"?>
<realty-feed xmlns="http://webmaster.yandex.ru/schemas/feed/realty/2010-06">
<generation-date>2010-10-05T16:36:00+04:00</generation-date>
...
</realty-feed>
现在我明白了:
<?xml version="1.0"?>
<realty-feed>
...
</realty-feed>
我的序列化器代码片段:
$xmlEncoder = new XmlEncoder('realty-feed');
$normalizer = new CustomNormalizer();
$serializer = new Serializer(array($normalizer),array($xmlEncoder));
$output = $serializer->serialize($objectData, 'xml');
我解决了我的问题。我创建了自己的类,并编写了与默认类XmlEncoder中相同的方法,但对一些标准的公共和私有方法进行了一些更改。
class N1XmlEncoder extends SerializerAwareEncoder implements EncoderInterface, DecoderInterface, NormalizationAwareInterface
{
...
/**
* {@inheritdoc}
*/
public function encode($data, $format, array $context = array())
{
if ($data instanceof \DOMDocument) {
return $data->saveXML();
}
$xmlRootNodeName = $this->resolveXmlRootName($context);
$this->dom = $this->createDomDocument($context);
$this->format = $format;
$this->context = $context;
if (null !== $data && !is_scalar($data)) {
$root = $this->dom->createElementNS('http://webmaster.yandex.ru/schemas/feed/realty/2010-06', $xmlRootNodeName);
$dateTime = new \DateTime('now');
$dateTimeStr = $dateTime->format(DATE_ATOM);
$rootDate = $this->dom->createElement('generation-date', $dateTimeStr);
$this->dom->appendChild($root);
$root->appendChild($rootDate);
$this->buildXml($root, $data, $xmlRootNodeName);
} else {
$this->appendNode($this->dom, $data, $xmlRootNodeName);
}
return $this->dom->saveXML();
}
...
private function createDomDocument(array $context)
{
$document = new \DOMDocument('1.0','utf-8');
// Set an attribute on the DOM document specifying, as part of the XML declaration,
$xmlOptions = array(
// nicely formats output with indentation and extra space
'xml_format_output' => 'formatOutput',
// the version number of the document
'xml_version' => 'xmlVersion',
// the encoding of the document
'xml_encoding' => 'encoding',
// whether the document is standalone
'xml_standalone' => 'xmlStandalone',
);
foreach ($xmlOptions as $xmlOption => $documentProperty) {
if (isset($context[$xmlOption])) {
$document->$documentProperty = $context[$xmlOption];
}
}
return $document;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句