9

I have some XML generated with embedded Scala, but it does not put the generated XML on separate lines.

Currently, it looks like this,

<book id="0">
      <author>Gambardella, Matthew</author><publish_date>Sun Oct 01 00:00:00 EDT 2000</publish_date><description>An in-depth loo
k at creating applications with XML.</description><price>44.95</price><genre>Computer</genre><title>XML Developer's Guide</title>
    </book>

but I want it to look like this:

<book id="0">
  <author>Gambardella, Matthew</author>
  <publish_date>Sun Oct 01 00:00:00 EDT 2000</publish_date>
  <description>An in-depth look at creating applications with XML.</description>
  <price>44.95</price>
  <genre>Computer</genre>
  <title>XML Developer's Guide</title>
</book>

How can I control the formatting? Here is the code that generates the XML

<book id="0">
  { keys map (_.toXML) }
</book>

here is toXML:

def toXML:Node = XML.loadString(String.format("<%s>%s</%s>", tag, value.toString, tag))
tsjnsn
  • 441
  • 5
  • 12
  • Possible duplicate of [How to produce nicely formatted XML in Scala?](http://stackoverflow.com/questions/3364627/how-to-produce-nicely-formatted-xml-in-scala) – Suma Mar 23 '16 at 08:51

1 Answers1

17

Use a PrettyPrinter:

val xml = // your XML

// max width: 80 chars
// indent:     2 spaces
val printer = new scala.xml.PrettyPrinter(80, 2)

printer.format(xml)

By the way, you might want to consider replacing your toXML with:

def toXML: Node = Elem(null, tag, Null, TopScope, Text(value.toString))

This is probably faster and removes all kind of escaping issues. (What if value.toString evaluates to </a>?)

gzm0
  • 14,752
  • 1
  • 36
  • 64
  • Is there an alternative to `PrettyPrint` that returns as an XML `Node` rather than a `String`? I'd like to be able to `print` the formatted node directly without using the prettyprinter first. Right now I'm building the node, pretty printing, and then parsing back into a node `XML.loadString(prettyPrinter format xml)` Doesn't seem very efficient. – tsjnsn Jun 14 '13 at 15:03
  • @tsjnsn I do see what you mean. Apparently `XML.loadString` preserves non significant whitespace. This is not required behavior for an XML parser (see http://www.w3.org/TR/xml/#sec-white-space) unless specified in the document itself (and hence might change in the future). I recommend you to use the `PrettyPrinter` only once you actually need a `String`. – gzm0 Jun 14 '13 at 18:15