I am running this for loop:
for (i in 1:length(file_list)){
doc <- read_xml(file_list[i])
xml_ns(doc)
ns <- xml_find_all(doc, xpath_person, xml_ns(doc))
items<-xml_find_all(doc, "//d1:REPORT/d1:People/d1:ACRSPERSON")
nodenames<-xml_name(xml_children(items))
contents<-trimws(xml_text(xml_children(items)))
if (length(items) >0) {
itemindex<-rep(1:length(items), times=sapply(items, function(x) {length(xml_children(x))}))
person1<-data.frame(itemindex, nodenames, contents)
#Convert from long to wide format
person<- pivot_wider(person1, id_cols= itemindex, names_from = nodenames,
values_from = contents) # %>% unnest(cols = c(A, B, C, D))
out_person <- rbind.fill(out_person,person )
}
However when I run the code all at once (in markdown - feel like it worked in regular rscript) - I get the following error.
**Error in read_xml.character(file_list[i]) : Document is empty [4]**
I tried to add some kind of break but it did not work.
for (i in 1:length(file_list)){
doc <- read_xml(file_list[i])
xml_ns(doc)
ns <- xml_find_all(doc, xpath_person, xml_ns(doc))
items<-xml_find_all(doc, "//d1:REPORT/d1:People/d1:ACRSPERSON")
nodenames<-xml_name(xml_children(items))
contents<-trimws(xml_text(xml_children(items)))
if (length(items) >0) {
itemindex<-rep(1:length(items), times=sapply(items, function(x) {length(xml_children(x))}))
person1<-data.frame(itemindex, nodenames, contents)
#Convert from long to wide format
person<- pivot_wider(person1, id_cols= itemindex, names_from = nodenames,
values_from = contents) # %>% unnest(cols = c(A, B, C, D))
out_person <- rbind.fill(out_person,person )
if (is.null(file_list[i])){
break
}
}
}
How do I fix this so that the for loop runs correctly. When there are no more items in the file_list
the for loop closes successfully. Or is there something else which is causing the problem?
Thanks.
question from:
https://stackoverflow.com/questions/65889368/getting-unknown-error-at-the-end-of-a-for-loop-how-to-fix 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…