我有一些看起来像这样的XML:
<?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>
为了重现性,我用循环抓取了XML:
# 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)) }
而且我只是在大学的名字之后.我对XML知之甚少,但我发现这有效:
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 }
但是,我已经看到提到xmlXPathApply(),我想知道解析循环是否无法重写以使用它.
我被困的地方是我不知道如何为我想要的部分编写XPath,因为有多个节点具有相同的名称.
修好xml之后……
> plist = xmlParse('data.xml') > xpathSApply(plist,'/plist/array/dict/dict/string',xmlValue) [1] "-27.45433" "153.01474" [3] "-27.45706" "153.01239" [5] "university" "Queensland University of Technology" [7] "way" "26303436"
输出你可以正常索引.
但是,如果节点具有属性,例如< string type ='uniname“> …< / string>,那么您可以使用漂亮的”@“语法,如:
> xpathSApply(plist,'/plist/array/dict/dict/string[@type='uniname']',xmlValue)
另一种方式,对于这种plist格式化可能更好,是:
> sapply(getNodeSet(plist,'//key[text() = "name"]'),function(x) xmlValue(getSibling(x))) [1] "Queensland University of Technology"