Consider the following XML
example
library(xml2)
myxml <- read_xml('
<data>
<obs ID="a">
<name> John </name>
<hobby> tennis </hobby>
<hobby> golf </hobby>
<skill> python </skill>
</obs>
<obs ID="b">
<name> Robert </name>
<skill> R </skill>
</obs>
</data>
')
Here I would like to get an (R or Pandas) dataframe from this XML that contains the columns name
and hobby
.
However, as you see, there is an alignment problem because hobby
is missing in the second node and John has two hobbies.
in R, I know how to extract specific values one at a time, for instance using xml2
as follows:
myxml%>%
xml_find_all("//name") %>%
xml_text()
myxml%>%
xml_find_all("//hobby") %>%
xml_text()
but how can I align this data correctly in a dataframe? That is, how can I obtain a dataframe as follows (note how I join with a |
the two hobbies of John):
# A tibble: 2 × 3
name hobby skill
<chr> <chr> <chr>
1 John tennis|golf python
2 Robert <NA> R
In R, I would prefer a solution using xml2
and dplyr
. In Python, I want to end-up with a Pandas dataframe. Also, in my xml there are many more variables I want to parse. I would like a solution that has allows the user to parse additional variables without messing too much with the code.
Thanks!
EDIT: thanks to everyone for these great solutions. All of them were really nice, with plenty of details and it was hard to pick up the best one. Thanks again!
In R, I'd probably use
and maybe do some polishing using
df[df==""] <- NA
andtrimws()
to remove whitespaces.Or:
pandas
How It Works
et = ET.parse('my_data.xml')
etree.findall('obs')
returns a list of elements within thexml
structure that are'obs'
tagspd.Series
constructorobs2series
obs2series
I loop through all child nodes in one'obs'
element.defaultdict
defaults to alist
meaning I can append to a value even if the key hasn't been seen before.pd.Series
to get a series of lists.pd.Series.str.join('|')
I convert this to a series of strings as I wanted.pd.DataFrame
constructor.A general R solution that does not require to hardcode the variables.
Using
xml2
and tidyverse'spurrr
:What it does:
obs
, find and store the node names in that obs.obs
, collapse them and store in a list.rbind
(implicit inmap_df()
) each 'flatted' list into the resultingdata.frame
.Data:
XML
Create a function that can handle missing or multiple nodes, and then apply that to the
obs
nodes. I added the id column so you can see how to usexmlGetAttr
too (use"."
for the obs node and the leading"."
on other nodes so its relative to that current node in the set).xml2
I don't use
xml2
very often, but maybe get theobs
nodes and then applyxml_find_all
if there are duplicate tags instead of usingxml_find_first
.I tested both methods using the
medline17n0853.xml
file at the NCBI ftp. This is a 280 MB file with 30,000 PubmedArticle nodes, and the XML package took 102 seconds to parse pubmed ids, journals and combine multiple publication types. The xml2 code ran for 30 minutes and then I killed it, so that may not be the best solution.