Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert XML using XSLT in R

Tags:

r

xml

xslt

I have task currently being performed by SQL Server Reporting Services where it exports a dataset to an XML format using an XSLT that converts the typical schema to a bespoke one. In order to replace this report, I need to be able to similarly transform XML when the user wants to download it.

The end layout produced by XSLT is horrible - it involves padding and all sorts of whacky concatenations and I'd rather not reinvent the wheel by doing the whole transformation in the first conversion from data to XML.

My google-fu has failed me: how do I convert XML via an XSLT using R?

MWE

Here is a script that uses iris data and converts it to XML (I use my package from CRAN purely to keep the code level down on the example). I then have an XSLT (on gist) that when I run the XML through in Visual Studio converts the XML but I don't know how to translate that activity into R.

library(optiRum)
library(XML)
irisdata<-convertToXML(iris)
saveXML(irisdata,"iris.xml")
like image 775
Steph Locke Avatar asked Mar 18 '23 08:03

Steph Locke


1 Answers

I think you're looking for Sxslt package, just using example data

library("Sxslt")
library("XML")
files <- sapply(c("sqrt.xml", "sqrt.xsl"), function(f) system.file("examples", f, package = "Sxslt"))

Where files[1] is an xml file and files[2] is an xsl file

xmlParse(files[[1]])

<?xml version="1.0"?>
<test>
  <sqrt>9</sqrt>
  <date/>
  <code>mean(rnorm(10000))</code>
</test>

Then use Sxslt to apply stylesheet

xsltApplyStyleSheet(files[1], files[2])

Gives

$doc
<?xml version="1.0" standalone="yes"?>
<HTML>
  <body>
 sqrt: 3
 pow: 81
 date: Thu Jan 15 06:46:54 2015<i class="output">-0.0140224652198879</i>
  substring: an(rnor</body>
</HTML>


$stylesheet
An object of class "XSLStyleSheet"
Slot "ref":
<pointer: 0x108ef2a60>


$status
OK 
 0 

attr(,"class")
[1] "XMLInternalXSLTDocument"

Extra guidance on installing Sxslt

  • You will need to install libxslt-dev on your linux machine first
  • The latest build no longer works with R 3.1.2, nor will it install from source further to Bug #1 on it's repo. The kind raiser of the bug took a fork and fixed the package so you can use devtools::install_github("cboettig/Sxslt") to install it.

That version is no longer up, but you can use:

install.packages("remotes")
remotes::install_github("omegahat/Sxslt")
like image 81
sckott Avatar answered Mar 20 '23 15:03

sckott