我有一堆带有envelope
元素的XML。每个人的内部都是一个阵列。数组中的每一行都有2个元素。第一个是标识符,第二个是我想要抓取的文本。我需要行的第一个值来标识正确的行,以便我可以获取正确的值。
在下面的例子中,我的行中有'food',用代码610954
表示。我希望在此代码之后抓取2个元素(c('pizza', 'burger')
。同样,代码605380
表示'饮料'。我想抓住c('coke', 'pepsi')
。我怎样才能使用 xml2 包要做到这一点吗?
library(xml2)
library(magrittr)
myxml <- read_xml('
<inside>
<envelope>
<card-entries type="array">
<card-entry>
<card-id type="integer">605380</card-id>
<value>coke</value>
</card-entry>
<card-entry>
<card-id type="integer">610954</card-id>
<value>pizza</value>
</card-entry>
</card-entries>
</envelope>
<envelope>
<card-entries type="array">
<card-entry>
<card-id type="integer">605380</card-id>
<value>pepsi</value>
</card-entry>
<card-entry>
<card-id type="integer">610954</card-id>
<value>burger</value>
</card-entry>
</card-entries>
</envelope>
</inside>
'
)
## as far as I can parse it (but not specific enough)
myxml %>%
xml_find_all('//envelope/card-entries[@type="array"]/card-entry') %>%
xml_text()
food <- -CODE THAT GIVES HERE c('pizza', 'burger')- # 610954
drinks <- -CODE THAT GIVES HERE c('coke', 'pepsi')- # 605380
答案 0 :(得分:3)
您可以像这样修改原始方法来获取饮料:
myxml %>%
xml_find_all('//envelope/card-entries[@type="array"]/card-entry[card-id = "605380"]/value') %>%
xml_text()
#[1] "coke" "pepsi"
但你可以采用其他各种方法
# get following sibling called value
myxml %>%
# foods
xml_find_all('//card-id[text()="610954"]/following-sibling::value') %>%
xml_text()
#[1] "pizza" "burger"
# get following::value[1] - Specify [1] or you would get all following values,
# including "pepsi". With value[1] you get only the following value.
myxml %>%
# foods
xml_find_all('//card-id[text()="610954"]/following::value[1]') %>%
xml_text()
#[1] "pizza" "burger"
# look for value nodes with a preceding sibling with the appropriate card-id
myxml %>%
# drinks
xml_find_all('//value[preceding-sibling::card-id[text()="605380"]]') %>%
xml_text()
#[1] "coke" "pepsi"
# Get value node that is a child of card-entry nodes with the appropriate card-id.
# specifically looking in envelope elements
myxml %>%
# drinks
xml_find_all('//envelope/card-entries/card-entry[card-id = "605380"]/value') %>%
xml_text()
#[1] "coke" "pepsi"
# less specific
myxml %>%
xml_find_all('//card-entry[card-id = "605380"]/value') %>%
xml_text()
#[1] "coke" "pepsi"
答案 1 :(得分:2)
如下:
library(tidyverse)
library(stringr)
myxml %>%
xml_find_all('//envelope/card-entries[@type="array"]/card-entry') %>%
xml_text() %>%
map(.f = str_sub, start = c(1, 7), end = c(6, 1000000L)) %>%
reduce(rbind) %>%
as_tibble() %>%
mutate(type = ifelse(V1 == 605380, yes = "drinks", no = "food"))
然后你可以轻松地分别分配饮料和食物。