# Generating HTML report Dynamically from a template
library(XML)
search()
objects(2)
# We can use the xmlOutputDOM function to create HTML dynamically
# We use a super simple example that creates a little snippet of HTML
testDom = xmlOutputDOM()
class(testDom)
names(testDom)
# The value function returns the value of the document
testDom$value()
# Note that it starts with a begin and end tag
# We insert tags into this tree
args(testDom$addTag)
args(testDom$closeTag)
# Add a list tag
testDom$addTag("ol", attrs= c("example" ="AK", "extra" = "Hi"), close=FALSE)
testDom$value()
testDom$addTag("li", "This is my first idea", close=TRUE)
testDom$addTag("li", "This is my first second", close=TRUE)
testDom$closeTag("ol")
testDom$value()
testDom$addTag("ul", close=FALSE)
testDom$addTag("li", "This is my another idea", close=TRUE)
testDom$addTag("li", "And yet another", close=TRUE)
testDom$closeTag("ul")
subTree = testDom$value()
class(subTree)
subTree[[1]]
subTree[[2]]
# We can write it out using the save XML function
saveXML(test, file="myTest.xml")
# We can read the template into R with the htmlTreeParse function
myTree = htmlTreeParse("template.html", asTree = TRUE)
myTree
class(myTree)
myRoot = xmlRoot(myTree)
xmlSApply(myRoot[[2]], xmlName)
# Here is one of the include tags
# One way to find these tags is with recursions
# move through the tree looking for xmlName of include
# and replace with the appropirate xmlNode
myRoot[[2]][[5]]
myRoot[[2]][[5]] = subTree[[1]]
myRoot[[2]][[5]]
class(myRoot)
saveXML(myRoot, file="xyz.xml")
# An alternative is to let the tree parser find these tags for you.
# To do this we would write a handler.
# The following shows how we can use global variables as inputs to
# the insertTag handler function
whichState = 2
insertHandlers =
function()
{
includeTag = function(x) {
subTree[[ whichState ]]
}
list(include = includeTag)
}
myNewTree = htmlTreeParse("template.html", asTree = TRUE,
handlers=insertHandlers())
myNewRoot = xmlRoot(myNewTree)
# Notice that where the include tag appeared in the original tree
# we now have a node from another tree.
# we could have called another funtion to dynamically generate
# this replacement node and we could take input from the attributes
# in the include node as well as arguments from the user.
myNewRoot[[2]][[5]]
myNewRoot[[2]][[7]]
saveXML(myNewRoot, file = "myHandlerReport.html")