在R中从XML创建DataFrame报错:无法将xml_nodeset转为dataframe
问题:从XML提取气象数据转换为DataFrame报错
我尝试从XML中提取windDirection、windSpeed的属性数据,以及对应的from和to时间戳,但转换为DataFrame时持续报错。
我使用的代码尝试
第一种尝试(xml2包)
library(xml2) as_list(wind_data <- read_xml("https://metwdb-openaccess.ichec.ie/metno-wdb2ts/locationforecast?lat=51.6547167;long=-9.7734153")) # Wind direction direction <- wind_data %>% xml_find_all("//windDirection") direction %>% xml_attr("deg") %>% as.numeric() # Wind speed speed <- wind_data %>% xml_find_all("//windSpeed") speed %>% xml_attr("mps") %>% as.numeric() # to and from time <- wind_data %>% xml_find_all("//time") time %>% xml_attr("from") %>% as.character() time %>% xml_attr("to") %>% as.character() wind_data <- data.frame(direction, speed, time)
第二种尝试(XML包)
library(XML) wind_data <- xmlToDataFrame(time, direction, speed)
报错信息
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘xmlToDataFrame’ for signature ‘"xml_nodeset", "xml_nodeset", "xml_nodeset", "missing", "missing"’
解决方案
问题出在你直接将xml_nodeset对象(节点集合)传入data.frame或xmlToDataFrame,而没有提取节点的实际属性值,同时xmlToDataFrame的参数用法不符合要求。以下是正确的处理方式:
方法:用xml2 + purrr遍历节点提取数据
这种方式能确保每个时间节点对应的风向、风速数据一一对应,避免长度不匹配的问题:
library(xml2) library(dplyr) library(purrr) # 读取XML数据 wind_xml <- read_xml("https://metwdb-openaccess.ichec.ie/metno-wdb2ts/locationforecast?lat=51.6547167;long=-9.7734153") # 获取所有time节点 time_nodes <- xml_find_all(wind_xml, "//time") # 遍历每个time节点,提取对应数据并组合成DataFrame wind_df <- map_dfr(time_nodes, function(node) { # 提取时间戳 from_time <- xml_attr(node, "from") to_time <- xml_attr(node, "to") # 提取当前time节点下的风向(deg属性) wind_dir <- xml_find_first(node, ".//windDirection") %>% xml_attr("deg") %>% as.numeric() # 提取当前time节点下的风速(mps属性) wind_speed <- xml_find_first(node, ".//windSpeed") %>% xml_attr("mps") %>% as.numeric() # 返回单条数据记录 tibble( from = from_time, to = to_time, wind_direction_deg = wind_dir, wind_speed_mps = wind_speed ) }) # 查看结果 head(wind_df)
关键说明
- 避免直接使用xml_nodeset对象:必须通过
xml_attr()提取节点的属性值(比如deg、mps、from),得到数值或字符向量后再构建DataFrame。 - 按时间节点关联数据:每个
time节点下对应一组风向、风速数据,通过遍历time节点的方式,能保证数据的对应关系不会错乱。 - xmlToDataFrame的正确用法:XML包的
xmlToDataFrame需要传入XML文档或单个节点集合,不支持多个nodeset参数,对于嵌套结构的XML,遍历节点的方式更灵活可靠。
内容的提问来源于stack exchange,提问作者hannahb
相关产品推荐
相关产品推荐

