fileName <- system.file("exampleData", "mtcars.xml", package="XML")
# Print the name of each XML tag encountered at the beginning of each
# tag.
# Uses the libxml SAX parser.
xmlEventParse(fileName,
list(startElement=function(name, attrs){cat(name,"")}),
useTagName=FALSE, addContext = FALSE)
# Parse the text rather than a file or URL by reading the URL's contents
# and making it a single string. Then call xmlEventParse
xmlURL <- "http://www.omegahat.org/Scripts/Data/mtcars.xml"
xmlText <- paste(scan(xmlURL, what="",sep="\n"),"\n",collapse="\n")
xmlEventParse(xmlText, asText=TRUE)
# Using a state object to share mutable data across callbacks
f <- system.file("exampleData", "gnumeric.xml", package = "XML")
zz <- xmlEventParse(f,
handlers = list(startElement=function(name, atts,.state) {
state = .state + 1
print(.state)
.state}), state = 0)
print(zz)
if(libxmlVersion()$major >= 2) {
startElement = function(x, ...) cat(x, "")
xmlEventParse(file(f), handlers = list(startElement = startElement))
xmlConnection =
function(con) {
if(is.character(con))
con = file(con, "r")
if(isOpen(con, "r"))
open(con, "r")
function(len) {
if(len < 0) {
close(con)
return(character(0))
}
x = character(0)
tmp = ""
while(length(tmp) > 0 && nchar(tmp) == 0) {
tmp = readLines(con, 1)
if(length(tmp) == 0)
break
if(nchar(tmp) == 0)
x = append(x, "")
else
x = tmp
}
if(length(tmp) == 0)
return(tmp)
x = paste(x, collapse="")
print(x)
x
}
}
ff = xmlConnection(f)
xmlEventParse(ff, handlers = list(startElement = startElement))
}Run the code above in your browser using DataLab