[英]Symfony Serializer XML add custom attribute to root node
When generating an XML file with Serializer component (in Symfony4) I want to add a custom attribute to the root node but I can't figure out how to.在使用 Serializer 组件(在 Symfony4 中)生成 XML 文件时,我想向根节点添加一个自定义属性,但我不知道怎么做。
The docs mention how to name the root node, but not how to add custom attributes. 文档提到了如何命名根节点,但没有提到如何添加自定义属性。
In my service I have:在我的服务中,我有:
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'
]);
This generates:这会产生:
<?xml version="1.0" encoding="utf-8"?>
<document>
// ...
</document>
But I want something like this:但我想要这样的东西:
<?xml version="1.0" encoding="utf-8"?>
<document id="123" lang="Eng">
// ...
</document>
I don't know what I'm missing.我不知道我错过了什么。 Thank you for the help.
感谢您的帮助。
Ok, I figured it out.好的,我想通了。
Reading more about the XmlEncoder I saw that in order to add attributes to a node you use the @
symbol and the #
for the value.阅读有关XmlEncoder的更多信息,我看到为了向节点添加属性,您使用
@
符号和#
作为值。
Since the serialize()
creates the root node automatically and wraps it around my entity's data, I just needed to define it first, along with my entity, and then pass it to the serialize method like so:由于
serialize()
自动创建根节点并将其包装在我的实体数据周围,因此我只需要先定义它以及我的实体,然后将其传递给 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'
]);
And now it produces the result I was after.现在它产生了我想要的结果。 Hope this helps anyone in the future.
希望这对将来的任何人都有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.