XML data into data.frame table

Viewed 23

I have this code:

# Downloading data from IMF via JSON
u.xml <- "http://dataservices.imf.org/REST/SDMX_XML.svc/CompactData/IFS/Q..BFDA_BP6_USD.?startPeriod=2000&endPeriod=2022"
## parse the xml document and get the top-level XML node
doc <- xmlParse(u.xml)
top <- xmlRoot(doc)

Now, my question is how to turn top into a data.frame table? Thank you very much!

P.S. Desired data.frame table looks like this:

  FREQ REF_AREA INDICATOR      UNIT_MULT  TIME_FORMAT  TIME_PERIOD OBS_VALUE
1 Q    BS       BFDA_BP6_USD   6          P3M          2000-Q1     0
2 Q    BS       BFDA_BP6_USD   6          P3M          2000-Q2     0
...
1 Answers

Assuming you need all Series nodes and given XML is atteibute-centric, consider the undocumented method, xmlAttrsToDataFrame. However, be sure to assign a prefix for the default namespace in parent tag DataSet in order to run XPath on Series elements:

nmsp <- c(data = "http://dataservices.imf.org/compact/IFS") 

imf_series_df <- XML:::xmlAttrsToDataFrame(
    getNodeSet(doc, path="//data:Series", namespaces=nmsp)
)
Related