Variable in CDATA in Scala
Asked Answered
M

2

14

Is there a way to put a variable to be expanded in a cdata section in scala

val reason = <reason><![CDATA[ {failedReason} ]]></reason>
Mountaineer answered 20/12, 2012 at 16:19 Comment(0)
F
14

I am not sure if you can get that through native XML support, but you could do something like:

scala.xml.XML.loadString("<reason><![CDATA[%s]]></reason>".format(failedReason))

You lose some of the compile-time validations that way, but it should give you am xml element with the data which you are looking for. Since it returns a scala.xml.Elem, you can also embed the result in a larger XML structure.

EDIT

After thinking about this a bit more, the following may be a beter (and less fragile) way to do this. It restricts the free-text portion to only the CDATA, minimizing the potential for unbalanced expressions.

<reason>{ scala.xml.Unparsed("<![CDATA[%s]]>".format(failedReason)) }</reason> 
Ferroconcrete answered 20/12, 2012 at 16:37 Comment(0)
M
27

It could be even simplier:

val reason = <reason>{scala.xml.PCData(failedReason)}</reason>
Malvasia answered 14/3, 2013 at 13:59 Comment(2)
You might want to escape illegal ]]>: content.replaceAll("]]>", "]]]]><![CDATA[>")Mulloy
I'm not sure the comment by @BrunoBieth applies to this (great!) answer. It already correctly deals with "gotcha" strings: <reason>{scala.xml.PCData("]]>")}</reason> becomes <reason><![CDATA[]]]]><![CDATA[>]]></reason>Taper
F
14

I am not sure if you can get that through native XML support, but you could do something like:

scala.xml.XML.loadString("<reason><![CDATA[%s]]></reason>".format(failedReason))

You lose some of the compile-time validations that way, but it should give you am xml element with the data which you are looking for. Since it returns a scala.xml.Elem, you can also embed the result in a larger XML structure.

EDIT

After thinking about this a bit more, the following may be a beter (and less fragile) way to do this. It restricts the free-text portion to only the CDATA, minimizing the potential for unbalanced expressions.

<reason>{ scala.xml.Unparsed("<![CDATA[%s]]>".format(failedReason)) }</reason> 
Ferroconcrete answered 20/12, 2012 at 16:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.