2

I am trying to retrieve data in R from an oData source. This script worked, but after i updated some packages, the script required the xml2 package, which caused an error.

library('httr') # for sending http requests
library("xml2") # for reading xml

# log start of request
log_message(paste("Requesting OData from:",url))

# get the OData resource
response <- GET(url,authenticate(usr,pwd))

# parse xml docucument
responseContent <- content(response,type="text/xml")

# determine the names of the attributes
xmlNames <- xpathApply(responseContent,
                        '//ns:entry[1]//m:properties[1]/d:*',xmlName, 
                        namespaces = c(ns = "http://www.w3.org/2005/Atom",
                                       m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata",
                                       d="http://schemas.microsoft.com/ado/2007/08/dataservices"))

When determining the names of the attributes i get the following error. Does anyone know what this error message means and how I can solve it?

Error in UseMethod("xpathApply") : no applicable method for 'xpathApply' applied to an object of class "c('xml_document', 'xml_node')"

omi
  • 23
  • 1
  • 6
  • Welcome to Stack overflow omi. Please take a look at [how to ask](http://stackoverflow.com/help/how-to-ask) good questions. You may also find this [R example making link helpful](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) - I recommend you show `library(packages)` in yoru code above and use `sessionInfo()` to give the names of versions so people can try track down your error. – micstr Feb 18 '16 at 11:12
  • Another tip - Please check out `packrat` package which lets you freeze/choose/rollback your package versions so you don't have this drama. Its from Rstudio so if you are using their IDE it will be easy to implement. – micstr Feb 18 '16 at 11:14

1 Answers1

5

httr switched to using xml2 recently in v1.1.0 i think. If you use content(x) on xml data you get an xml2 object back. You can do that, and do something like (not tested)

xml_find_all(x, '//ns:entry[1]//m:properties[1]/d:*', xml_ns(x))

or parse to text like content(x, as = "text"), which gives you character string, then do XML::xmlParse(), then you can proceed as normal with your XML based workflow

sckott
  • 5,755
  • 2
  • 26
  • 42
  • Thanks @sckott, I decided to switch back to a previous version of httr to avoid this problem for the time being. – omi Feb 19 '16 at 12:36
  • note that with the new httr you also have to set encoding explicitly, usually `content(..., encoding = "UTF-8")` – sckott Feb 19 '16 at 17:31