Search code examples
xmlscaladocumentcreation

How do you add xml document info with scala.xml?


First of all:

  • I am aware of anti-xml, and scales, but I would like to use standard scala.xml
  • I prefer to build xml document using explicit methods, not with implicit xml syntax built into Scala

Ok, so I have such piece of code:

val text = new scala.xml.Text("just a text")
val root = new scala.xml.Elem(null,"element",null,scala.xml.TopScope,text)
val doc = new scala.xml.Document()
doc.docElem = root
println(doc.toString())

Almost good but as result I get:

<element>just a text</element>

and I would like to get XML header too, like:

<?xml version="1.0"?>
<element>just a text</element>

Question: How to add it?

Of course in common-sense way, not some hacking with extra verbatim println with header ;-).


Solution

  • The only solution I've found is to add the following code

    val writer : PrintWriter = new PrintWriter(System.out)
    XML.write(writer,root,"utf-8",true,null)
    writer.flush()