Scala embedded XML document in PCDATA

Unfortunately, I have a requirement to create some messy XML.

The main document must contain an embedded XML document. However, the embedded document runs in the CDATA section. The end result should look something like this:

<?xml version="1.0"?> <foo> <xml> <![CDATA[ <?xml version="1.0" encoding="UTF-8"?> <bar> </bar> ]]> </xml> </foo> 

I ran into two problems:

Firstly, everything that is displayed in the CDATA section is displayed as escaped (for example, the sign greater than > becomes &gt; )

Is there a way to disable shielding in the CDATA section?

Secondly, I cannot create an XML declaration. When I try to include an embedded XML document, I get the following exception:

 def serializeEmbedded(): Seq[Node] = { <?xml version="1.0"?> <bar> </bar> } Exception in thread "main" java.lang.IllegalArgumentException: xml is reserved at scala.xml.ProcInstr.<init>(ProcInstr.scala:25) 

This is my first foray into Scala's native XML processing.

Thanks,

Saish

+4
source share
1 answer

An XML declaration is really relevant only for serialization, and you cannot specify it using the Scala XML syntax literal (as you discovered).

I would suggest defining an auxiliary function as follows:

 import scala.xml._ def toCData(doc: Elem) = { val w = new java.io.StringWriter XML.write(w, doc, "UTF-8", true, null) PCData(w.toString) } 

Now you can write, for example:

 scala> val doc = <outer>{ toCData(<inner/>) }</outer> doc: scala.xml.Elem = <outer><![CDATA[<?xml version='1.0' encoding='UTF-8'?> <inner></inner>]]></outer> 

It is not as elegant as it may be, with a bit more language support, but it works.

+5
source

Source: https://habr.com/ru/post/1432331/


All Articles