Scala: Saving/writing XML to a file

Problem: You want to write XML data to a file in a Scala application, such as saving application data or configuration information to a file.


Use the method to write a Scala literal to a file. Given this XML literal:

// create an XML variable
val portfolio = 
      <reit>Super REIT 1</reit>

write the literal to file with the save method:

// save the XML to a file"portfolio.xml", portfolio)

This creates a plain-text file named portfolio.xml in the current directory, containing the XML literal shown.

As with any file-writing code, beware that can throw an exception:

scala>"/foo/bar/baz", portfolio) /foo/bar/baz (No such file or directory)

Additional save parameters

The save method lets you specify other parameters, including the encoding to use, whether or not to write an XML declaration, and whether or not to write a DOCTYPE declaration.

To write the data to a file with encoding information, use this approach:"portfolio.xml", portfolio, "UTF-8", true, null)

This results in the following header being added to the file:

<?xml version='1.0' encoding='UTF-8'?>

To add a DOCTYPE to the file, first import the necessary classes:

import scala.xml.dtd.{DocType, PublicID}

Then create a DocType instance, and save the file with that instance:

val doctype = DocType("html",
  PublicID("-//W3C//DTD XHTML 1.0 Strict//EN",
  Nil)"portfolio.xml", portfolio, "UTF-8", true, doctype)

With this configuration, the following DOCTYPE line is added to the output file:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

The scala.xml package also includes a Utility object with a small collection of useful methods that let you sort node attributes, trim elements, remove comments, and more.

Pretty printing

If it’s important that the XML can be easily read by a human being, it’s best to use the PrettyPrinter class to make sure the XML is “human readable.” But because the PrettyPrinter returns a String, you’ll need to write it to a file using another method. I have my own FileUtils class, so the process looks like this:

val portfolio =
    <reits><reit>Super REIT 1</reit></reits>

// 80 characters wide, 2 character indentation
val prettyPrinter = new scala.xml.PrettyPrinter(80, 2)
val prettyXml = prettyPrinter.format(portfolio)"portfolio.xml", prettyXml)

See Also