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

Error in the code while trying to read from URL using XML, xmlParse

提问人:Moh 提问时间:4/25/2023 最后编辑:Gilles QuénotMoh 更新时间:4/25/2023 访问量:25

问:

我必须阅读下面的链接,并在代码 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)))
     

问题是 记录总共有多少条记录?提取记录 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 url xml 解析 数据提取

评论


答:

0赞 G5W 4/25/2023 #1

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

datValue <- xpathApply(xml_data, datPath, xmlValue)

所以不包含 XML,只包含值。您需要使用datValue

text_value <- datValue[[11]]