Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Scala as a Replacement for XSLT?

Tags:

xml

scala

xslt

On my Scala project we have a lot of legacy XSLT and was wondering if we should convert the XSLT to Scala code.

I like XSLTs approach of applying templates to nodes, and am fine using it for purely DOM transformations, but don't think it's well suited for processing data within the XML document (hard to read and test) - I'd rather use Scala to do that.

Given Scala's built-in XML support and pattern matching I thought it may be a good replacement. Has anyone successfully converted XSLT scripts to Scala? Are there any patterns or best practices?

I'm aware of an old project to convert XSLT to Scala Source code called XSLT2src, but that has been dormant for a long time and doesn't support XSLT2.

Thanks

like image 760
ChucK Avatar asked Jun 24 '11 08:06

ChucK


2 Answers

It's hard to tell for sure without knowing exactly what XML you want to transform and how, but as things stand XSLT template/match are both more powerful and more readable than Scala XML pattern matching, which has a number of issues.

In particular:

  • any non-trivial matching is either impossible or very hard to do
  • namespaces are not supported

So you might be better off calling Saxon from Scala to perform these transformations.

Still, you might want to look at the chapter on XML from Programming Scala.

Finally, the prevalent opinion these days is that the built-in XML support in Scala is lacking in many ways. See e.g. Anti-XML for a project that aims at building something better.

like image 135
ebruchez Avatar answered Sep 21 '22 14:09

ebruchez


Scales Xml provides matching on namespaces and attributes directly but also provides a more flexible internal dsl for handling XPaths (as well as string based evaluation).

Perhaps most interesting for transformations is its ability to fold over paths, select what you want in an XPath and transform the results "in place". These transformation rules can be combined.

You could still replicate much of xslt approach with direct XPath usage in Scales and transforming/building the trees as you would in xslt.

like image 42
Chris Avatar answered Sep 18 '22 14:09

Chris