首页 > 解决方案 > 将网络要素服务读入 R data.frame

问题描述

我有这个功能可以将 Web Feature Service 读入 R data.frame。我已将它用于此url,并且我设法将 WFS 作为数据框。

require(RCurl)
require(XML)

readWFS_monitoringsites <- function(url){
  #Function to read a WFS and return a dataframe
  cat(url,"\n")

  # Dealing with https:
  if(substr(url,start = 1,stop = 5)=="http:"){
    getSites.xml <- xmlInternalTreeParse(url)
  } else {
    tf <- getURL(url, ssl.verifypeer = FALSE)

    getSites.xml <- xmlParse(tf)
  }

  ds <- xmlToDataFrame(getNodeSet(getSites.xml, "//emar:MonitoringSiteReferenceData"))

  ds$Source <- url
  ds
}


df_sites <- readWFS_monitoringsites("https://hbmaps.hbrc.govt.nz/arcgis/services/emar/MonitoringSiteReferenceData/MapServer/WFSServer?request=GetFeature&service=WFS&typename=MonitoringSiteReferenceData&srsName=urn:ogc:def:crs:EPSG:6.9:4326&Version=1.1.0")

当我更改此网址的功能时

readWFS_regulatoryIRIS <- function(url){
  #Function to read a WFS and return a dataframe
  cat(url,"\n")

  # Dealing with https:
  if(substr(url,start = 1,stop = 5)=="http:"){
    getSites.xml <- xmlInternalTreeParse(url)
  } else {
    tf <- getURL(url, ssl.verifypeer = FALSE)

    getSites.xml <- xmlParse(tf)
  }

  ds <- xmlToDataFrame(getNodeSet(getSites.xml, "//emar:RegulatoryIRIS"))

  ds$Source <- url
  ds
}
df_iris <- readWFS_regulatoryIRIS("https://hbmaps.hbrc.govt.nz/arcgis/services/WebMaps/RegulatoryIRIS/MapServer/WFSServer?request=GetFeature&service=WFS&typename=WebMaps_RegulatoryIRIS:All_Consents&srsName=urn:ogc:def:crs:EPSG:6.9:4326&Version=1.1.0")

我收到了这个错误

xpathApply.XMLInternalDocument(doc, path, fun, ..., namespaces = namespaces, : 错误评估 xpath 表达式 //emar:RegulatoryIRIS

我将非常感谢任何解决此错误的建议。

标签: rxml

解决方案


错误消息的关键部分是您省略的第一行:-)

 XPath error : Undefined namespace prefix

您的 XPath 表达式“//emar:RegulatoryIRIS”指的是名称空间前缀emar。您可以在对 getNodeSet() 的调用中定义它,或者最好在文档的根/顶级节点中定义它。

在我今天从该特定 URL 检索到的 4 个文档中,只有一个是根注释中定义的 xmlns:emar="http://www.lawa.org/nz/emar"。但是,即使使用该名称空间前缀-> URL 映射,也没有名为RegulatoryIRIS 的节点。

而在其他 3 个文档中,有诸如 WebMaps_RegulatoryIRIS:All_Consents 之类的节点名称,它们在命名空间前缀中带有RegulatoryIRIS 字样,而不是节点名称。

因此,要么 URL 返回具有不同 XML 结构的内容,要么您需要更好地理解 XML 的结构,或者两者兼而有之。

但是错误来自 emar 不是定义的命名空间前缀。最好在调用 getNodeSet() 时指定这一点,例如,

getNodeSet(doc, "//emar:RegulatoryIRIS", c(emar = "http://www.lawa.org.nz/emar"))

高温高压


推荐阅读