【问题标题】:How do I parse this xml document in r?如何在 r 中解析这个 xml 文档?
【发布时间】:2018-10-19 13:38:21
【问题描述】:

我在寻找店铺名称和店铺坐标来自:http://contact.woolworths.com.au/storelocator/service/proximity/supermarkets/latitude/-37.7510/longitude/144.8981/range/50/max/200.xml

例如
<name>Niddrie</name>
<latitude>-37.737332</latitude>
<longtitude>144.892342</longtitude>

我该怎么做?我试过这些:

library(XML)
library(methods)
library(xml2)

#https://stackoverflow.com/questions/17198658/how-to-parse-xml-to-r-data-frame 
data <- xmlParse("http://contact.woolworths.com.au/storelocator/service/proximity/supermarkets/latitude/-37.7510/longitude/144.8981/range/50/max/200.xml")
xml_data <- xmlToList(data)
location <- as.list(xml_data[["storeList"]][["storeRank"]][["storeDetail"]][["Name"]])

#https://www.datacamp.com/community/tutorials/r-data-import-tutorial#xml - not working
xmlfile <- xmlTreeParse("http://contact.woolworths.com.au/storelocator/service/proximity/supermarkets/latitude/-37.7510/longitude/144.8981/range/50/max/200.xml")
class(xmlfile)
topxml <- xmlRoot(xmlfile)
topxml <- xmlSApply(topxml,
                    function(x) xmlSApply(x, xmlValue))
xml_df <- data.frame(t(topxml),
                     row.names=NULL) 

两者都没有错误,但不是我想要的名称。与坐标相同。

【问题讨论】:

标签: r xml xml-parsing


【解决方案1】:

看起来 XML 只能来自 API。它确实有一个命名空间,所以这很可能是导致您出现问题的原因。我们将删除它。

library(xml2)

xml_ns_strip(
  doc <- read_xml("http://contact.woolworths.com.au/storelocator/service/proximity/supermarkets/latitude/-37.7510/longitude/144.8981/range/50/max/200.xml")
) -> doc

data.frame(
  name = xml_text(xml_find_all(doc, ".//storeDetail/name")),
  lng = xml_double(xml_find_all(doc, ".//storeDetail/longtitude")),
  lat = xml_double(xml_find_all(doc, ".//storeDetail/latitude")),
  stringsAsFactors = FALSE
) -> stores

str(stores)
## 'data.frame': 188 obs. of  3 variables:
##  $ name: chr  "Niddrie" "Highpoint West" "Moonee Ponds" "East Keilor" ...
##  $ lng : num  145 145 145 145 145 ...
##  $ lat : num  -37.7 -37.8 -37.8 -37.7 -37.7 ...

对于那些仍在使用XML?:

library(XML)

doc <- xmlParse("http://contact.woolworths.com.au/storelocator/service/proximity/supermarkets/latitude/-37.7510/longitude/144.8981/range/50/max/200.xml")

def <- c(d = getDefaultNamespace(doc)[[1]]$uri)

data.frame(
  name = xpathSApply(doc, "//d:storeDetail/d:name", xmlValue, namespaces = def),
  lng = as.numeric(xpathSApply(doc, "//d:storeDetail/d:longtitude", xmlValue, namespaces = def)),
  lat = as.numeric(xpathSApply(doc, "//d:storeDetail/d:latitude", xmlValue, namespaces = def)),
  stringsAsFactors = FALSE
) -> stores

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多