Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 435
greenoldman Avatar asked Jan 22 '12 21:01

greenoldman


People also ask

What is Scala XML?

Scala treats XML as the first-class citizen. So, instead of embedding XML documents into strings. , you can place them inline in your code like you place an int or double value. For example. scala> val xml = Hello. xml: scala.xml.Elem = Hello.

What is XML document node?

Everything in an XML document is a node. For example, the entire document is the document node, and every element is an element node. Root node. The topmost node of a tree. In the case of XML documents, it is always the document node, and not the top-most element.

What should every XML file contain?

All XML documents must contain a single tag pair to define a root element. All other elements must be within this root element. All elements can have sub elements (child elements). Sub elements must be correctly nested within their parent element.

What is XML used for?

What is XML Used For? XML is one of the most widely-used formats for sharing structured information today: between programs, between people, between computers and people, both locally and across networks. If you are already familiar with HTML, you can see that XML is very similar.


1 Answers

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()
like image 100
Nikolay Ivanov Avatar answered Oct 12 '22 16:10

Nikolay Ivanov