---
title: "Transforming XML with XSL"
output: html_notebook
---

This tutorial shows to define and apply XSL transformations to an XML document to produce a new XML or other text representation of the information. Knowledge of XML, DTD, and XPath is presumed. Uses the **xslt** package in addition to **XML**.

```{r}
if (!require(XML)) install.packages('XML')
  library(XML)

if (!require(xslt)) install.packages('xslt')
  library(xslt)
```

```{r}
fp <- "/Users/mschedlb/OneDrive/Teaching/IS2000.Materials/Recitations"
xmlFile <- "cdcatalog.xml"
xslFile <- "cdcatalog.xsl"
txnFile <- "cdcatalog.html"

xmlDoc <- read_xml(paste(fp,xmlFile,sep="/"))
xslStyle <- read_xml(paste(fp,xslFile,sep="/"))

transformedXML <- xml_xslt(xmlDoc, xslStyle)

status <- write_xml(transformedXML, file = paste(fp,txnFile,sep="/"))

cat(as.character(transformedXML))
```

```{r}
fp <- "C:/Users/mjs01/OneDrive/Teaching/IS2000.Materials/Recitations"
xmlFile <- "inventory.xml"
xslFile <- "invent2winry.xsl"
txnFile <- "wineriesOUT.xml"

xmlDoc <- read_xml(paste(fp,xmlFile,sep="/"))
xslStyle <- read_xml(paste(fp,xslFile,sep="/"))

transformedXML <- xml_xslt(xmlDoc, xslStyle)

status <- write_xml(transformedXML, file = paste(fp,txnFile,sep="/"))

cat(as.character(transformedXML))
```

## Play Area: XPath Expressions

The play area below is for trying out XPath expression to ensure they return what is expected before using the XPath in an XSL file.

```{r}
fp <- "/Users/mschedlb/OneDrive/Teaching/IS2000.Materials/Recitations"
xmlFn <- "TeamRosters.xml"

xmlDoc <- xmlParse(validate = F, file = paste(fp,xmlFn,sep="/"))

xpathExpr <- "/rosters/team[@name='Boston Bruins']"

x <- xpathSApply(xmlDoc, xpathExpr)

x
```

## Apply XSL

```{r}
library(XML)
library (xslt)

fp <- "/Users/mschedlb/OneDrive/Teaching/IS2000.Materials/Recitations"
xmlFn <- "TeamRosters.xml"
xslFn <- "Rosters2StatsXSL.xsl"
txnFn <- "BruinsStats.xml"
xmlFile <- paste(fp,xmlFn,sep="/")
xslFile <- paste(fp,xslFn,sep="/")
txnFile <- paste(fp,txnFn,sep="/")

xmlObj <- xmlParse(file = xmlFile, validate = F)

xmlDoc <- read_xml(xmlFile)
xslStyle <- read_xml(xslFile)

transformedXML <- xml_xslt(xmlDoc, xslStyle)

status <- write_xml(transformedXML, file = txnFile)

cat(as.character(transformedXML))

xmlTxnObj <- xmlParse(file = transformedXML, validate = F)
df <- xmlToDataFrame(xmlTxnObj,
                     colClasses = c("character",
                                    "integer",
                                    "integer"))

head(df)
```
