尝试使用 XML、xmlParse 读取 URL 时代码出错

问题描述 投票:0回答:1

我必须阅读以下链接并在代码后回答以下问题 http://www.ggobi.org/book/data/australian-crabs.xml

      library(XML)
crabs <- xmlParse('http://www.ggobi.org/book/data/australian-crabs.xml')
root <- xmlRoot(crabs)
xmlName(root)
varInfo <- root[[1]][[2]]
varInfo

as.vector(unlist(xmlApply(varInfo, xmlAttrs)))
     

问题是

records
总共有多少条记录?提取记录 11.

的文本值

**我的答案是**

library(XML)

# download the xml data and save it in a file
url <- "http://www.ggobi.org/book/data/australian-crabs.xml"
download.file(url, destfile = "australian-crabs.xml")

# parse the xml data
xml_data <- xmlParse("australian-crabs.xml")

# extract the data from the xml
datPath <- "//record"
datValue <- xpathApply(xml_data, datPath, xmlValue)

# find the total number of records
num_records <- length(datValue)
cat("Total number of records:", num_records, "\n")

# extract the text value for record 11
record11 <- xmlParse(datValue[11])
text_value <- xmlValue(getNodeSet(record11, ".//text")[[1]])
cat("Text value for record 11:", text_value, "\n")

但是我有以下错误

trying URL 'http://www.ggobi.org/book/data/australian-crabs.xml'
Content type 'application/xml' length 20212 bytes (19 KB)
==================================================
downloaded 19 KB

Total number of records: 208 
Error in file.exists(file) : invalid 'file' argument

我需要解决这个错误

r xml url xml-parsing extract
1个回答
0
投票

您在运行时已经提取了记录的值

datValue <- xpathApply(xml_data, datPath, xmlValue)

所以

datValue
不包含xml,只包含值。你需要使用

text_value <- datValue[[11]]
© www.soinside.com 2019 - 2024. All rights reserved.