2016-09-19 81 views
2

雖然這個問題可以用其他編程語言來解答,但我覺得它從Scala中錯過了。如何精美地表示一個Scala類中的XML實體?

我想要使用清晰的DSL代表Scala類中的以下示例XML,以便我可以在REST(play)框架的XML中輕鬆使用它。

<?xml version="1.0" encoding="UTF-8"> 
<requests> 
    <request type="foo" id="1234"> 
    <recipient>bar<recipient> 
    <recipient>baz<recipient> 
    <body>This is an example string body</body> 
    <ext>Optional tag here like attachments</ext> 
    <ext>Optional too</ext> 
    </request> 
</requests> 

這裏是我試圖表現在斯卡拉類上面的模型:

class Attribute[G](
    value:G 
) 

class Request(
    type: Attribute[String], 
    id: Attribute[Integer], 
    recipient[List[String]], 
    body: String, 
    ext: Option[List[String]] // Some or None 
) 

// how it's used 
val requests = List[Request] 

這不是功課,我試着寫劇本的應用程序翻譯從一個公司內部的其餘部分一個行業標準之一。 (如果有人很好奇,這是OpenCable ESNI vI02 XML格式)

我的問題:我是否正確表示「foo」和「id」屬性?如果是這樣,我怎麼會輕鬆輸出XML沒有太多的按摩或粗糙的字符串插值。我希望foo和id被解釋爲屬性而不是嵌套標籤,如下所示:

...<request><type>foo</type><id>1234</id>...DO NOT WANT 

謝謝!

回答

2

XML標籤是Scala中的第一類公民,可以讓您以比其他語言更清晰的方式使用標籤。

從Scala 2.11起,XML Library已被提取到its own package

有了這樣的,你可以很容易地使用一些慣用的Scala實現自己的目標:

case class Request(requestType: String, id: Int, recipients: List[String], body: String, ext: Option[List[String]]){ 

     def toXML = 
     <requests> 
      <request type={requestType} id={id}> 
       {recipientsXML} 
       <body>{body}</body> 
       {extXML} 
      </request> 
     </requests> 

     private def recipientsXML = 
     recipients.map(rec => <recipient>{rec}</recipient>) 
     private def extXML = for { 
     exts <- ext 
     elem <- exts 
     } yield <ext>{elem}</ext> 
} 
+0

你忘了XML標記周圍雙引號的高清toxml用於? – dlite922

相關問題