英文:
XML Formatting from Kotlin class
问题
我尝试从Kotlin数据类中格式化XML,并且在属性方面遇到了问题。问题是如何向一个字段添加属性,尝试格式化类似于以下内容:
<ExampleClass>
<field actionCode="Add">aa</field>
</ExampleClass>
通过以下方式:
data class ExampleClass (
@JacksonXmlProperty(isAttribute = true, localName = "actionCode")
var fieldActionCode: String = "Add",
@JacksonXmlProperty(localName = "field")
var field: String = "aa"
)
但这样做会将属性放在错误的位置,放在Example类中:
<ExampleClass actionCode="Add">
<field>aa</field>
</ExampleClass>
我使用FasterXML Jackson库。
英文:
I am trying to format XML from Kotlin data class and I have a problem with attributes. Question is how to add attribute to one field, trying to format something like this:
<ExampleClass>
<field actionCode="Add">aa</field>
</ExampleClass>
By this:
data class ExampleClass (
@JacksonXmlProperty(isAttribute = true, localName = "actionCode")
var fieldActionCode: String = "Add",
@JacksonXmlProperty(localName = "field")
var field: String = "aa"
)
But by doing so attribute goes to wrong place, to Example class:
<ExampleClass actionCode="Add">
<field>aa</field>
</ExampleClass>
I use FasterXML Jackson library.
答案1
得分: 0
属性放在正确的位置,因为您将 fieldActionCode
声明为 ExampleClass
的属性,而不是其嵌套元素。
期望的输出可以通过以下方式实现:
data class ExampleClass (
@field:JacksonXmlProperty(localName = "field")
var field: ExampleField = ExampleField()
) {
data class ExampleField(
@field:JacksonXmlProperty(isAttribute = true, localName = "actionCode")
var fieldActionCode: String = "Add",
@field:JacksonXmlText
var field: String = "aa"
)
}
fun main() {
val mapper = XmlMapper().enable(SerializationFeature.INDENT_OUTPUT)
println(mapper.writeValueAsString(ExampleClass()))
}
产生的输出是:
<ExampleClass>
<field actionCode="Add">aa</field>
</ExampleClass>
英文:
Attribute goes to correct place since you declare fieldActionCode
as an attribute of ExampleClass, not of its nested element.
Desired output can be achieved like this:
data class ExampleClass (
@field:JacksonXmlProperty(localName = "field")
var field: ExampleField = ExampleField()
) {
data class ExampleField(
@field:JacksonXmlProperty(isAttribute = true, localName = "actionCode")
var fieldActionCode: String = "Add",
@field:JacksonXmlText
var field: String = "aa"
)
}
fun main() {
val mapper = XmlMapper().enable(SerializationFeature.INDENT_OUTPUT)
println(mapper.writeValueAsString(ExampleClass()))
}
Produces:
<ExampleClass>
<field actionCode="Add">aa</field>
</ExampleClass>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论