2014-08-31 26 views
2

任何人都可以告訴我如何將「xml」標籤寫入輸出嗎?正如預期的那樣,loadString()方法在加載時擺脫它。如何使用scala.xml和Play Framework編寫<?xml>標籤

object SitemapController extends Controller { 

    def validDeals = Action { implicit request => 
    val xmlStr = "<?xml version="1.0" encoding="UTF-8"?><msg>There's no xml tag</msg>" 
    Ok(scala.xml.XML.loadString(xmlStr)) 
    } 
} 

我從控制器獲得貝克只是

<msg>There's no xml tag</msg> 

回答

2

OKStatus,它採用了Writable類型類的內容,以字節(see Status.apply)進行編碼。查看源here,用於xml節點的Writable僅調用toString。基本上,而不是帶有xml聲明的文檔,您只需獲取根節點的字符串表示形式。

要獲得decl,您需要撥打XML.write()並使用java.io.WriterxmlDecl = true以及其他參數。 (我能夠爲DocType提供null,而不是發明一個)。

你可以寫一個StringWriter的,然後發送,但我認爲最有效的方式(特別是如果您的文檔比較大),將創建一個隱含Writablexml.Node覆蓋內置的一個。

0

Play在處理XML時非常愚蠢。 M.B。沒有多少人使用它? 無論如何,這裏是可寫的構成適當的xml文件,也可以修剪空格。 只需將其導入控制器。

object Implicits {  
    implicit def writeableOf_Node(implicit codec: Codec): Writeable[NodeSeq] = { 
     Logger.debug(s"Codec: $codec") 
     Writeable{ xml => { 
     val stringWriter = new StringWriter(1024) 
     val node = scala.xml.Utility.trim(xml(0)) 
     scala.xml.XML.write(stringWriter, node, codec.charset, xmlDecl = true, null) 
     val out = codec.encode(stringWriter.toString) 
     stringWriter.close() 
     out 
     }} 
    } 
    } 
相關問題