XML files to dataframe

Viewed 44

I have would like to read XML 860 files.

All xml files have the structure

<ip id_pac="48">
      <rodcis>48</rodcis>
      <jmeno>Andrew</jmeno>
      <prijmeni>Mazal</prijmeni>
      <titul_pred></titul_pred>
      <titul_za></titul_za>
      <dat_dn format="D">1999-06-21</dat_dn>
      <dat_de format="D"></dat_de>
      <sex>M</sex>
      <rod_prijm></rod_prijm>
      <a typ="1">
        <dat_od format="D">2020-09-17</dat_od>
      </a>
    </ip>

And I would like to get data frame where one column is "rodcis" (in this case 48) and second column "dat_od" (in this case 2020-09-17)

I am trying this

  1. Get all XML files
    files <- list.files(path = "~/Downloads/XML", 
                        pattern = "*.xml",
                        full.names = TRUE)
  1. Get a list (out) with all 860 XML files to
    out <- lapply(files, xmlParse)
  1. List to dataframe
    dataframe <- do.call(rbind, lapply(out, function(x) rootnode[[1]][[2]], rootnode[[2]][[1]]))

But an error occurs that I don't understand.

cannot coerce type 'externalptr' to vector of type 'list'

1 Answers

Here is a possible solution using the xml2 package. See the comments in the code for the step by step guide.

library(xml2)
library(dplyr)

#loop through the file list with lapply
dfs <-lapply(files, function(file) {
   #read file
   page <- read_xml(file)
   
   #get id for each file
   id <- xml_find_first(out, "//ip") %>% xml_attr("id_pac") 
   
   #get information from each the requested nodes
   rodcis <- xml_find_first(out, ".//rodcis") %>% xml_text()
   datod <- xml_find_first(out, ".//dat_od") %>% xml_text()
   
   #make data frame of results for each file
   data.frame(id, rodcis, datod)
})

#combine all results into 1 data frame
answer <- bind_rows(dfs)
Related