Home > Mobile >  how can i parse xml to csv and save it in R?
how can i parse xml to csv and save it in R?

Time:10-07

How can I parse my xml data and save it as csv in R? Please see the input and output below

Input =

<patient id="559" weight="99" insulin_type="Novalog">
<glu_level>
<event ts="18-01-2022 00:01:00" value="179"/>
<event ts="18-01-2022 00:06:00" value="183"/>
<event ts="18-01-2022 00:11:00" value="187"/>
</glu_level>
<finger_stick>
<event ts="07-12-2021 01:03:20" value="107"/>
<event ts="07-12-2021 01:08:04" value="107"/>
<event ts="07-12-2021 05:08:14" value="191"/>
<event ts="07-12-2021 11:21:49" value="586"/>
</finger_stick>
</patient>

Output1 =

time glu_level
18-01-2022 00:01:00 179
18-01-2022 00:06:00 183
18-01-2022 00:11:00 187

CodePudding user response:

We may read the file read_xml, extract the attributes after filtering for the 'glu_level'

library(xml2)
library(dplyr)
dat <- read_xml("input.xml")
glu <- dat %>% 
          xml_find_all("//glu_level/event") 
out <- tibble(time = glu %>% 
                xml_attr('ts'), glu_level = glu %>% 
                                          xml_attr('value'))         

-output

> out
# A tibble: 3 × 2
  time                glu_level
  <chr>               <chr>    
1 18-01-2022 00:01:00 179      
2 18-01-2022 00:06:00 183      
3 18-01-2022 00:11:00 187     
  • Related