Mary Jane
Mary Jane

Reputation: 139

Scala: how to write nodeBuffer to a single xml file

I am trying to write multiple elements to a single xml file.

If I enclose <elem1> and <elem2> in a root element <root></root>, at the beginning and end of getXML(), getXML() will return an Elem, resulting in the scala.xml.XML.save(...) method working.

However, this is not an option for me. Please show me how to write multiple elements into a single xml file.

def getXML(): NodeBuffer = {
  <elem1>hello</elem1>
  <elem2>Sample text</elem2>
}

val test = getXML()
scala.xml.XML.save("test2.xml", test, "UTF-8", false, null) // Does not works

Upvotes: 1

Views: 899

Answers (1)

Martijn
Martijn

Reputation: 12112

scala.xml.XML.save stores a single Node (i.e. a single root element)

Storing multiple xml documents (i.e. multiple root nodes) in a single file is not supported directly by the API.

Instead, just render each Node in the buffer as String (possibly using scala.xml.PrettyPrinter), and write each string to a file through your preferred means of writing strings to files.

However doing this probably is a bad idea. Having files with multiple XML root elements is asking for troubles.

Upvotes: 1

Related Questions