2017-07-05 5 views
0

jaxbを使用してScalaオブジェクトをXMLにシリアル化する(ScalaネイティブXML機能を使用しない)このコードをScalaで記述しました。ScalaでJAXBを使用して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は、あなたは注釈を再定義し、それらを使用するためにScalaのタイプを使用する必要があります

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

答えて

0

です。 以下のコードを参照して、使用される大文字と小文字の区別があることに注意してください。 セッションのためである、のXmlElementの名前は私が期待した文字列を取得クラスに

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) 

FooBarの中で、フィールド上にありません、他のポイント:ここでは

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

が完了要旨一例ですさらに、0..1カーディナリティをOption にマッピングするアダプタhttps://gist.github.com/javathought/658c0554145ae6b7f89bd34ca71d8e0e – Javathought

関連する問題