我正在努力抓取依赖.atomsvc文件的公共数据源,以允许用户在Excel中设置数据Feed。我使用XML库提取URL,在R中构建了一个非常脆弱的解析器。我想知道如何在xml2中完成这项工作(最好以更简洁和优雅的方式)
以下是我使用XML库
的方式'constants'
据我所知,xml2版本
# Crystal Reports Parser Sample
library(XML)
library(dplyr)
# Get the .atomsvc file from the Export to Data Feed Option on the PA DEP website
pa_string <- '<?xml version="1.0" encoding="utf-8" standalone="yes"?><service xmlns:atom="http://www.w3.org/2005/Atom" xmlns:app="http://www.w3.org/2007/app" xmlns="http://www.w3.org/2007/app"><workspace><atom:title>Oil_Gas_Well_Production</atom:title><collection href="http://www.depreportingservices.state.pa.us/ReportServer?%2FOil_Gas%2FOil_Gas_Well_Production&P_PERIOD_ID=198&P_COUNTY%3Aisnull=True&P_CLIENT%3Aisnull=True&P_PERMIT_NUM%3Aisnull=True&P_OGO_NUM%3Aisnull=True&P_PRODUCING%3Aisnull=True&rs%3AParameterLanguage=&rs%3ACommand=Render&rs%3AFormat=ATOM&rc%3ADataFeed=xAx0x2"><atom:title>Tablix1</atom:title></collection></workspace></service>'
pa_list <- pa_string %>% xmlParse() %>% xmlToList()
# Extract the URL
URL <- URLdecode(pa_list$workspace$collection$.attrs)
我不知道如何从这里提取URL,或者如果这是考虑如何思考这个问题的正确方法。任何帮助都将非常感激!
答案 0 :(得分:0)
这是一种方法,通过从指定节点中提取属性:
library(xml2)
library(tidyverse)
pa_string <- '<?xml version="1.0" encoding="utf-8" standalone="yes"?><service xmlns:atom="http://www.w3.org/2005/Atom" xmlns:app="http://www.w3.org/2007/app" xmlns="http://www.w3.org/2007/app"><workspace><atom:title>Oil_Gas_Well_Production</atom:title><collection href="http://www.depreportingservices.state.pa.us/ReportServer?%2FOil_Gas%2FOil_Gas_Well_Production&P_PERIOD_ID=198&P_COUNTY%3Aisnull=True&P_CLIENT%3Aisnull=True&P_PERMIT_NUM%3Aisnull=True&P_OGO_NUM%3Aisnull=True&P_PRODUCING%3Aisnull=True&rs%3AParameterLanguage=&rs%3ACommand=Render&rs%3AFormat=ATOM&rc%3ADataFeed=xAx0x2"><atom:title>Tablix1</atom:title></collection></workspace></service>'
pa_string %>%
read_xml() %>%
xml_find_all("//*[name()='collection']")%>%
xml_attr("href")
#output
[1] "http://www.depreportingservices.state.pa.us/ReportServer?%2FOil_Gas%2FOil_Gas_Well_Production&P_PERIOD_ID=198&P_COUNTY%3Aisnull=True&P_CLIENT%3Aisnull=True&P_PERMIT_NUM%3Aisnull=True&P_OGO_NUM%3Aisnull=True&P_PRODUCING%3Aisnull=True&rs%3AParameterLanguage=&rs%3ACommand=Render&rs%3AFormat=ATOM&rc%3ADataFeed=xAx0x2"
xpath:
#// - Recursive descent; searches for the specified element at any depth.
#* - Matches any element node
#[ ] - Applies a filter pattern.
#name()='collection' - self explanatory
更短:
pa_string %>%
read_xml() %>%
xml_find_all("//@href") #select all attributes with name `href`
因为只有一个带有属性的元素,所以也可以这样做:
pa_string %>%
read_xml() %>%
xml_find_all("//@*") #Matches any attribute node