I have some XML that looks like:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
<dict>
<key>bbox.NE.lat</key>
<string>-27.45433</string>
<key>bbox.NE.lon</key>
<string>153.01474</string>
<key>bbox.SW.lat</key>
<string>-27.45706</string>
<key>bbox.SW.lon</key>
<string>153.01239</string>
<key>crs</key>
<string>EPSG 4326</string>
<key>found</key>
<string>1</string>
</dict>
<array>
<dict>
<key>bbox</key>
<dict>
<key>bbox.NE.lat</key>
<string>-27.45433</string>
<key>bbox.NE.lon</key>
<string>153.01474</string>
<key>bbox.SW.lat</key>
<string>-27.45706</string>
<key>bbox.SW.lon</key>
<string>153.01239</string>
</dict>
<key>centroid</key>
<dict>
<key>lat</key>
<dict>
<key>lat</key>
<string>-27.45513</string>
<key>lon</key>
<string>153.0137</string>
</dict>
</dict>
<key>id</key>
<string>33037721</string>
<key>properties</key>
<dict>
<key>amenity</key>
<string>university</string>
<key>name</key>
<string>Queensland University of Technology</string>
<key>osm_element</key>
<string>way</string>
<key>osm_id</key>
<string>26303436</string>
</dict>
</dict>
</array>
</array>
</plist>
For reproducibility's sake, I grabbed the XML with a loop:
# initialize the vector
queries<-(0)
# loop over coordinates - signups$latlong is just a vector of coordinates
# signups$latlong[1] = "51.5130004883%20-0.1230000034
# the space between lat & long is URL encoded
for(i in 1:length(signups$latlong)){
#self-imposed rate-limiting
Sys.sleep(0.05)
# if query returns an error, write NA and move on, also output to console so I can keep an eye on it
if(class(try(queries[i]<- getURL(paste("http://geocoding.cloudmade.com/[API KEY HERE]/geocoding/v2/find.plist?object_type=university&around=",signups$latlong[i],"&results=5&distance=closest", sep="")), silent=T))=="try-error")
{
queries[i]<-NA
print("NA")
print(i)
}
# just a progress indicator
else(print(i))
}
and I'm just after the name of the university. I don't know much about XML, but I've figured out that this works:
pagetree<-(0)
for (i in 1:length(queries)){
plist<-xmlTreeParse(queries[i])$doc$children$plist
nodes<-getNodeSet(plist, "//array//array//dict")
if(class(try(pagetree[i]<-xmlValue(nodes[[5]][[4]]), silent = T))=="try-error") pagetree[i]<-NA
}
However, I've seen mention of xmlXPathApply()
and I am wondering if the parsing loop couldn't be re-written to use it.
Where I'm stuck is that I don't know how to write the XPath for the piece I want, because there are multiple nodes with the same name.
Don't be hesitant to suggest a better way to do the error handling, as well.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…