Last active
December 15, 2015 02:49
-
-
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.)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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