[英]Symfony Serializer XML add custom attribute to root node
在使用 Serializer 組件(在 Symfony4 中)生成 XML 文件時,我想向根節點添加一個自定義屬性,但我不知道怎么做。
文檔提到了如何命名根節點,但沒有提到如何添加自定義屬性。
在我的服務中,我有:
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()
自動創建根節點並將其包裝在我的實體數據周圍,因此我只需要先定義它以及我的實體,然后將其傳遞給 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'
]);
現在它產生了我想要的結果。 希望這對將來的任何人都有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.