Symfony Serializer XML 添加自定义属性到根节点
Symfony Serializer XML add custom attribute to root node
当使用 Serializer 组件(在 Symfony4 中)生成 XML 文件时,我想将自定义属性添加到根节点,但我不知道该怎么做。
docs提到如何命名根节点,但没有提到如何添加自定义属性。
在我的服务中我有:
use Symfony\Component\Serializer\Serializer;
// ..
// $this->serializer is auto-wired
$this->serializer->serialize($myEntityObjectToSerialize, 'xml', [
'xml_format_output' => true,
'xml_encoding' => 'utf-8',
'xml_root_node_name' => 'document'
]);
这会生成:
<?xml version="1.0" encoding="utf-8"?>
<document>
// ...
</document>
但我想要这样的东西:
<?xml version="1.0" encoding="utf-8"?>
<document id="123" lang="Eng">
// ...
</document>
我不知道我错过了什么。
谢谢你的帮助。
好的,我明白了。
阅读有关 XmlEncoder 的更多信息,我看到为了向节点添加属性,您使用 @
符号和 #
作为值。
由于 serialize()
自动创建根节点并将其包装在我的实体数据周围,我只需要先定义它以及我的实体,然后将其传递给序列化方法,如下所示:
$rootNode = [
'@id' => 12345,
'@lang' => 'Eng',
'#' => $myEntityObjectToSerialize
]
// $this->serializer is auto-wired
$this->serializer->serialize($rootNode, 'xml', [
'xml_format_output' => true,
'xml_encoding' => 'utf-8',
'xml_root_node_name' => 'document'
]);
现在它产生了我想要的结果。
希望这对以后的任何人都有帮助。
当使用 Serializer 组件(在 Symfony4 中)生成 XML 文件时,我想将自定义属性添加到根节点,但我不知道该怎么做。
docs提到如何命名根节点,但没有提到如何添加自定义属性。
在我的服务中我有:
use Symfony\Component\Serializer\Serializer;
// ..
// $this->serializer is auto-wired
$this->serializer->serialize($myEntityObjectToSerialize, 'xml', [
'xml_format_output' => true,
'xml_encoding' => 'utf-8',
'xml_root_node_name' => 'document'
]);
这会生成:
<?xml version="1.0" encoding="utf-8"?>
<document>
// ...
</document>
但我想要这样的东西:
<?xml version="1.0" encoding="utf-8"?>
<document id="123" lang="Eng">
// ...
</document>
我不知道我错过了什么。 谢谢你的帮助。
好的,我明白了。
阅读有关 XmlEncoder 的更多信息,我看到为了向节点添加属性,您使用 @
符号和 #
作为值。
由于 serialize()
自动创建根节点并将其包装在我的实体数据周围,我只需要先定义它以及我的实体,然后将其传递给序列化方法,如下所示:
$rootNode = [
'@id' => 12345,
'@lang' => 'Eng',
'#' => $myEntityObjectToSerialize
]
// $this->serializer is auto-wired
$this->serializer->serialize($rootNode, 'xml', [
'xml_format_output' => true,
'xml_encoding' => 'utf-8',
'xml_root_node_name' => 'document'
]);
现在它产生了我想要的结果。 希望这对以后的任何人都有帮助。