asoft
sea

~ tiny vessels of code slowly floating out to sea

Powered by a motorboat called the S.S.Tumblr

1 year ago

@1:22am

2 notes
Comments

a well formed cupcake

Here’s a simple little sprinkle for anyone wondering how to serve xml with self-closing tags in Scala.

The basic cooking ingredients in Scala’s xml kitchen will output closing tags, even when the recipe does not call for them.

val selfClosingCupcake = <cupcake />

Will always unsuspectingly return

<cupcake></cupcake>

When your cupcakes are html tags, sometimes the extra closing tag is not valid.

The output

<link rel="stylesheet" href="cupcakes.css"></link>

may be tasty, but is less than valid.

The solution is simple. Sprinkle your xml with xml.Xhtml.

val selfClosingCupcake = xml.Xhtml.toXhtml(<cupcake/>)

This yields pretty much what you’d expect.

<cupcake/>

sweet teething

Beware of a few caveats.

Always put this call to toXhtml at the end of your processing pipeline as this returns a String rather than one of the handful of native xml types Scala provides.

If you were wondering, yes you can always step back into that native kitchen with XML.loadString

xml.XML.loadString(xml.Xhtml.toXhtml(<cupcake />))

Also of note.

Be aware of the xml api changes between Scala 2.7.* and 2.8.*

Scala 2.7.7.final requires you to pass in two extra args.

def toXhtml(n: Node, stripComment: Boolean, convertAmp: Boolean): String = {
  val sb = new StringBuilder()
  toXhtml(n, TopScope, sb, stripComment, convertAmp)
  sb.toString()
}

While Scala 2.8 blessed the community with default args.

def toXhtml(node: Node): String = sbToString(toXhtml(x = node, sb = _))
  1. coderspiel reblogged this from asoftsea
  2. asoftsea posted this
blog comments powered by Disqus