使用Scala中的JAXB序列化为XML

时间:2017-07-05 19:41:51

标签: scala jaxb

我在Scala中编写了这段代码,使用jaxb将Scala对象序列化为XML(不想使用Scala本机xml功能)。

@XmlRootElement(name = "SESSION")
@XmlAccessorType(XmlAccessType.FIELD)
case class Session(
   @XmlAttribute(name="TYPE")
   sessionType: String
) {
   def this() = this("")
}

@XmlRootElement(name = "FOO-BAR")
@XmlAccessorType(XmlAccessType.FIELD)
case class FooBar(
   @XmlElement
   session: Session
) {
   def this() = this(new Session())
}


object JAXBTest extends App {
   val context = JAXBContext.newInstance(classOf[FooBar])
   val fooBar = FooBar(Session("mysession"))
   val stringWriter = new StringWriter()
   val marshaller = context.createMarshaller()
   marshaller.marshal(hHonors, stringWriter)
   println(stringWriter.toString)
}

生成的XML看起来像

<FOO-BAR><session><sessionType>mysession</sessionType></session></FOO-BAR>

但我想要的XML是

<FOO-BAR><SESSION TYPE="mysession"></SESSION></FOO-BAR>

1 个答案:

答案 0 :(得分:1)

您必须使用scala type 重新定义注释并使用它们。 请参阅下面的代码并注意使用的案例敏感度。 另一点是Session,XmlElement的名称在FooBar的字段上而不在类

import io.github.javathought.commons.xml.Macros.{xmlAccessorType, xmlRootElement, xmlAttribute, xmlElement}


import scala.annotation.meta.field

object Macros {
  type xmlRootElement = XmlRootElement @companionClass
  type xmlAccessorType = XmlAccessorType @companionClass
  type xmlElement = XmlElement @field
  type xmlAttribute = XmlAttribute @field

}

@xmlAccessorType(XmlAccessType.FIELD)
case class Session(
                    @xmlAttribute(name="TYPE")
                    sessionType: String
                  ) {
  def this() = this("")
}

@xmlRootElement(name = "FOO-BAR")
@xmlAccessorType(XmlAccessType.FIELD)
case class FooBar(
                   @xmlElement(name = "SESSION")
                   session: Session
                 ) {
  def this() = this(new Session())
}

val hHonors = new FooBar(new Session("Hi"))

val context = JAXBContext.newInstance(classOf[FooBar])
val fooBar = FooBar(Session("mysession"))
val stringWriter = new StringWriter()
val marshaller = context.createMarshaller()
marshaller.marshal(hHonors, stringWriter)
println(stringWriter.toString)

我得到了预期的字符串:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><FOO-BAR><SESSION TYPE="Hi"/></FOO-BAR>