2

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.

3
  • Your XML is malformed, are you sure you are providing the real data? Dec 12, 2011 at 20:57
  • it was a formatting issue. It should be correct now. Dec 12, 2011 at 21:13
  • Yeah malformed XML is definitely a formatting issue Dec 13, 2011 at 6:55

1 Answer 1

3

After fixing the xml...

The way to traverse this with xpath is:

> 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" 

The output you can index like normal.

However, if the nodes had attributes, for example <string type='uniname">...</string>, then you could have used the nice "@" syntax like:

> xpathSApply(plist, '/plist/array/dict/dict/string[@type='uniname']', xmlValue)

Another way, which might be better for this plist formatting, is:

> sapply(getNodeSet(plist, '//key[text() = "name"]'), function(x) xmlValue(getSibling(x)))
[1] "Queensland University of Technology"
4
  • Thanks! So if I had about 14000 of the above XML blocks in an object called output, I could use something like for(i in length(output)) university[i]<-xpathSApply(plist[i], '/plist/array/dict/dict/string', xmlValue)[6] to get the values out? Dec 12, 2011 at 21:27
  • Yep, that sounds correct. Also see the alternative way I added, above, which might be better for the plist formatting.
    – John Colby
    Dec 12, 2011 at 21:32
  • 1
    I think query = '//string[text() = "university"]/following-sibling::string[1]/text()' used with xmlValue(plist[[query]]) gets the univsersity; I'd plist = xmlTreeParse(url, useInternalNodes=TRUE) without an explicit getUrl, and lapply over output rather than doing a loop. Dec 12, 2011 at 22:14
  • OK, that seems to address my follow-up, which is what to do if not all XML blocks have the same number of nodes. I'll give this a try. Martin, I didn't realize I could just use the URL directly in xmlTreeParse without fetching it first. If you want points, please submit it separately. Dec 12, 2011 at 22:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.