10

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 ;-).

greenoldman
  • 16,895
  • 26
  • 119
  • 185
  • 1
    You are using an awesome language like Scala where you could say `val xml = input ` and you dont prefer that? ;) Its okey, because its your choice, but could you tell me please why is it better to use the "other way"? – OverStack Jan 22 '12 at 23:22
  • @OverStack, Because this feature is a flaw actually. Word from me, it is very fragile to any typos, so you don't see your error until it bites you. Second thing -- the fact the featue exists, it does not mean you should use it. Word from others: http://www.codecommit.com/blog/scala/working-with-scalas-xml-support and there was a piece about HTML in VB, but I cannot find it right now. – greenoldman Jan 23 '12 at 08:14
  • @greenoldman Is it just me or your code gives a Null Pointer Exception? – Core_Dumped Dec 05 '13 at 10:05

1 Answers1

10

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()
Nikolay Ivanov
  • 8,897
  • 3
  • 31
  • 34
  • Thank you very much, it's odd that scala.xml does not have something more direct. – greenoldman Jan 23 '12 at 17:31
  • 2
    One more thing -- it is more useful (in general) to use `StringWriter` than `PrinterWriter` (because then it is very easy to get output xml as string). – greenoldman Jan 23 '12 at 17:44