Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating formatted XML in Scala

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))
like image 983
tsjnsn Avatar asked Jun 13 '13 20:06

tsjnsn


1 Answers

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>?)

like image 155
gzm0 Avatar answered Oct 17 '22 19:10

gzm0