Skip to content

Instantly share code, notes, and snippets.

@Ram-N
Last active December 15, 2015 02:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Ram-N/5189549 to your computer and use it in GitHub Desktop.
Save Ram-N/5189549 to your computer and use it in GitHub Desktop.
A simple function to recursively visit each node in a XML document. (Uses DT Lang's XML package.)
library(XML)
#Recursive Function to visit the XML tree (depth first)
visitNode <- function(node) {
if (is.null(node)) {
#leaf node reached. Turn back
return()
}
print(paste("Node: ", xmlName(node)))
num.children = xmlSize(node)
if(num.children == 0 ) {
# Add your code to process the leaf node here
print( paste(" ", xmlValue(node)))
}
#Go one level deeper
for (i in 1 : num.children) {
visitNode(node[[i]]) #the i-th child of node
}
}
xmlfile <- "books.xml"
#read the XML tree into memory
xtree <- xmlInternalTreeParse(xmlfile)
root <- xmlRoot(xtree)
visitNode(root)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment