当我序列化一个类ReturnValue
的实例时,我发现@XmlElement
不起作用。生成的xml仍然标记为<summary>
,而不是<comment>
。
ReturnValue类:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
data class ReturnValue(val type: String,
@XmlElement(name="comment")
val summary: String){
constructor(): this(type="java.lang.Object", summary="no summary")
}
测试程序:
fun main(args: Array<String>) {
val jaxbContext = JAXBContext.newInstance(ReturnValue::class.java)
val marshaller = jaxbContext.createMarshaller()
marshaller.marshal(
ReturnValue(type = "java.lang.Object",summary = "hello"),
System.out)
}
和输出:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><returnValue><type>type2</type><summary>hello</summary></returnValue>
所以,我想将<summary>
更改为<comment>
。我怎么能这样做?
答案 0 :(得分:6)
JAXB是一个Java API,它希望事物看起来像Java通常做的事情,而Kotlin做的事情略有不同。
要注释参数以使其看起来对JAXB正确,您必须使用HttpClientHandler handler = new HttpClientHandler();
handler.Proxy = System.Net.WebRequest.DefaultWebProxy;
handler.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
.....
HttpClient httpClient = new HttpClient(handler)
....
,以便将注释放在Kotlin参数转换为的Java字段上,如下所示:
@field:XmlElement
更多信息:Kotlin文档中的Annotation Use-site Targets。
答案 1 :(得分:0)
如果xml标记和属性是用大写字母编写的,则可以省略字段注释。我在使用一些常规字段和一些大写字段解析xml文件时遇到了问题。 @field:XmlElement
解决了这个问题,通过@ awd
fun main(args: Array<String>) {
val xml = """<?xml version="1.0" encoding="ISO-8859-1" ?>
<Root>
<Child>Text</Child>
</Root>"""
val jaxbContext = JAXBContext.newInstance(Root::class.java)
val unmarshaller = jaxbContext.createUnmarshaller()
val root = unmarshaller.unmarshal(xml.reader())
println(root)
val XML = """<?xml version="1.0" encoding="ISO-8859-1" ?>
<Root>
<CHILD>Text</CHILD>
</Root>"""
val JAXBCONTEXT = JAXBContext.newInstance(CapsRoot::class.java)
val UNMARSHALLER = JAXBCONTEXT.createUnmarshaller()
val ROOT = UNMARSHALLER.unmarshal(XML.reader())
println(ROOT)
val xmlField = """<?xml version="1.0" encoding="ISO-8859-1" ?>
<Root>
<Child>Text</Child>
</Root>"""
val jaxbContextField = JAXBContext.newInstance(RootField::class.java)
val unmarshallerField = jaxbContextField.createUnmarshaller()
val rootField = unmarshallerField.unmarshal(xml.reader())
println(rootField)
}
@XmlRootElement(name = "Root")
data class Root(var Child: String? = null)
@XmlRootElement(name = "Root")
data class CapsRoot(var CHILD: String? = null)
@XmlRootElement(name = "Root")
data class RootField(@field:XmlElement var Child: String? = null)
打印:
Root(Child=null)
CapsRoot(CHILD=Text)
RootField(Child=Text)