Scala: Displaying XML in a human-readable format (pretty printing)

Problem: You have some XML in a hard-to-read format in a Scala application, and want to print it in a format that’s easier to read, at least for humans.

Solution

Use the scala.xml.PrettyPrinter class. To see how it works, imagine starting with a long, continuous string of XML:

scala> val x = <pizza><topping>cheese</topping><topping>sausage</topping></pizza>
x: scala.xml.Elem =
   <pizza><topping>cheese</topping><topping>sausage</topping></pizza>

A quick look at the toString method shows that it prints the XML just as it was received:

scala> x.toString
res0: String = <pizza><topping>cheese</topping><topping>sausage</topping></pizza>

To print the XML in a more human-readable format, import the PrettyPrinter class, create a new instance of it, and format the XML as desired.

For instance, to improve the previous XML output, create a PrettyPrinter instance, setting the row width and indentation level as desired, in this case 80 and 4, respectively:

scala> val p = new scala.xml.PrettyPrinter(80, 4)
p: scala.xml.PrettyPrinter = scala.xml.PrettyPrinter@4a3a08ea

Formatting the XML literal returns a String, formatted as specified:

scala> p.format(x)
res1: String = 
<pizza>
    <topping>cheese</topping>
    <topping>sausage</topping>
</pizza>

As you might guess, the PrettyPrinter constructor looks like this:

PrettyPrinter(width: Int, step: Int)

The width is the maximum width of any row, and step is the indentation for each level of the XML.

There are other formatting methods available that let you specify namespace information, and a StringBuffer to append to. See the PrettyPrinter Scaladoc for more information.

See Also