R XML-将父节点和子节点(名称相同)合并到数据帧中
我有这样的XML:R XML-将父节点和子节点(名称相同)合并到数据帧中,r,xml,R,Xml,我有这样的XML: 1919 激怒 丹尼斯·佩特里奇 守门员 丹尼斯 佩特里奇 1988-05-24 83 187 1. 守门员 不为人知 2016-01-02 斯洛文尼亚 马修·米歇尔 守门员 马修 米歇尔 1991-09-04 Nîmes 法国 赖特 84 189 1. 守门员 不为人知 2016-08-18 法国 这里有一个可以尝试的解决方案。有关流程步骤的说明,请参见注释: library(xml2) library(dplyr) x <- read_xml('player.
1919
激怒
丹尼斯·佩特里奇
守门员
丹尼斯
佩特里奇
1988-05-24
83
187
1.
守门员
不为人知
2016-01-02
斯洛文尼亚
马修·米歇尔
守门员
马修
米歇尔
1991-09-04
Nîmes
法国
赖特
84
189
1.
守门员
不为人知
2016-08-18
法国
这里有一个可以尝试的解决方案。有关流程步骤的说明,请参见注释:
library(xml2)
library(dplyr)
x <- read_xml('player.xml')
Players3 <- x %>% xml_find_all('//Player')
dfs<-lapply(Players3, function(node){
#find names of all children nodes
childnodes<-node %>% xml_children() %>% xml_name()
#find the attr value from all child nodes
names<-node %>% xml_children() %>% xml_attr("Type")
#create columns names based on either node name or attr value
names<-ifelse(is.na(names), childnodes, names)
#find all values
values<-node %>% xml_children() %>% xml_text()
#create data frame and properly label the columns
df<-data.frame(t(values), stringsAsFactors = FALSE)
names(df)<-names
df
})
#bind together and add uid to final dataframe.
answer<-bind_rows(dfs)
answer$UID<- Players3 %>% xml_attr("uID")
answer
# Name Position first_name last_name birth_date weight height jersey_num real_position
# 1 Denis Petric Goalkeeper Denis Petric 1988-05-24 83 187 1 Goalkeeper
# 2 Mathieu Michel Goalkeeper Mathieu Michel 1991-09-04 84 189 1 Goalkeeper
# real_position_side join_date country birth_place first_nationality preferred_foot UID
# 1 Unknown 2016-01-02 Slovenia <NA> <NA> <NA> p40511
# 2 Unknown 2016-08-18 France Nimes France Right p119744
库(xml2)
图书馆(dplyr)
x%xml\u属性(“类型”)
#基于节点名称或属性值创建列名称
名称%xml\u text()
#创建数据框并正确标记列
答:是的,我看了那个问题。但两者之间有区别。在我的例子中,我得到了多个同名的节点“Stat”。举个例子。我希望将first_name作为列名,而不是Stat。