Efficiently transform XML to data frame

隐身守侯 提交于 2021-01-29 18:51:02

问题


I need to transform some vanilla xml into a data frame. The XML is a simple representation of rectangular data (see example below). I can achieve this pretty straightforwardly in R with xml2 and a couple of for loops. However, I'm sure there is a much better/faster way (purrr?). The XML I will be ultimately working with are very large, so more efficient methods are preferred. I would be grateful for any advice from the community.

library(tidyverse)
library(xml2)

demo_xml <- 
"<DEMO>
  <EPISODE>
    <item1>A</item1>
    <item2>1</item2>
  </EPISODE>
  <EPISODE>
    <item1>B</item1>
    <item2>2</item2>
  </EPISODE>
</DEMO>"


dx <- read_xml(demo_xml)

episodes <- xml_find_all(dx, xpath = "//EPISODE")
dx_names <- xml_name(xml_children(episodes[1]))

df <- data.frame()

for(i in seq_along(episodes)) {
  for(j in seq_along(dx_names)) {
    df[i, j] <- xml_text(xml_find_all(episodes[i], xpath = dx_names[j]))
  }
}

names(df) <- dx_names
df
#>   item1 item2
#> 1     A     1
#> 2     B     2

Created on 2019-09-19 by the reprex package (v0.3.0)

Thank you in advance.


回答1:


This is a general solution which handles a varying number of different sub-nodes for each parent node. Each Episode node may have different sub-nodes.
This strategy parses the children nodes identifying the name and values of each sub node. Then it converts this list into a longer style dataframe and then reshapes it into your desired wider style:

library(tidyr)
library(xml2)

demo_xml <- 
  "<DEMO>
  <EPISODE>
    <item1>A</item1>
    <item2>1</item2>
  </EPISODE>
  <EPISODE>
    <item1>B</item1>
    <item2>2</item2>
  </EPISODE>
</DEMO>"

dx <- read_xml(demo_xml)

#find all episodes
episodes <- xml_find_all(dx, xpath = "//EPISODE")
#extract the node names and values from all of the episodes
nodenames<-xml_name(xml_children(episodes))
contents<-trimws(xml_text(xml_children(episodes)))

#Idenitify the number of subnodes under each episodes for labeling
IDlist<-rep(1:length(episodes), sapply(episodes, length))

#make a long dataframe
df<-data.frame(episodes=IDlist, nodenames, contents, stringsAsFactors = FALSE)

#make the dataframe wide, Remove unused blank nodes:
answer <- spread(df[df$contents!="",], nodenames, contents)

#tidyr 1.0.0 version
#answer <- pivot_wider(df, names_from = nodenames, values_from = contents)


# A tibble: 2 x 3
  episodes item1 item2
     <int> <chr> <chr>
1        1 A     1    
2        2 B     2  



回答2:


This may be an option without using a for loop,

episodes <- xml_find_all(dx, xpath = "//EPISODE") %>% xml_attr("item1")
dx_names <- xml_name(xml_children(episodes[1]))

# You can get all values between the tags by xml_text()
values <- xml_children(episodes) %>% xml_text()


as.data.frame(matrix(values,
            ncol=length(dx_names),
            dimnames =list(seq(dx_names),dx_names),byrow=TRUE))

gives,

  item1 item2
1     A     1
2     B     2

Note that, you may need to change the Item2 column to a numeric one by as.numeric() since it's been assigned as factor by this solution.



来源:https://stackoverflow.com/questions/58007663/efficiently-transform-xml-to-data-frame

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!