解析R中的非嵌套XML标记

时间:2016-12-16 12:12:50

标签: r xml xml2

我正在尝试使用优秀的xml2 R库解析许多文档。例如,请考虑以下XML文件:

pg <- read_xml("https://www.theyworkforyou.com/pwdata/scrapedxml/westminhall/westminster2001-01-24a.xml")

其中包含多个<speech>标记,这些标记虽然未嵌套在<minor-heading><major-heading>个标记中,但已分开。我希望将此文档处理为具有以下结构的结果data.frame

     major_heading_id  speech_text
     heading_id_1       text1
     heading_id_1       text2
     heading_id_2       text3
     heading_id_2       text4

不幸的是,因为标签没有嵌套,我无法弄清楚如何做到这一点!我有成功恢复相关信息的代码(见下文),但将语音标签与各自的主要标题相匹配超出了我的范围。

我的直觉是,最好将XML文档拆分为标题标记,然后将每个文档作为单个文档处理,但我无法在xml2包中找到一个函数我会这样做的!

任何帮助都会很棒。

到目前为止我所处的位置:

speech_recs <- xml_find_all(pg, "//speech")
speech_text <- trimws(xml_text(speech_recs))

heading_recs <- xml_find_all(pg, "//major-heading")
major_heading_id <- xml_attr(heading_recs, "id")

1 个答案:

答案 0 :(得分:1)

您可以按照以下方式执行此操作:

require(xml2)
require(tidyverse)
doc <- read_xml("https://www.theyworkforyou.com/pwdata/scrapedxml/westminhall/westminster2001-01-24a.xml")

# Get the headings
heading_recs <- xml_find_all(doc, "//major-heading")

# path creates the structure you want
# so the speech nodes that have exactly n headings above them.
path <- sprintf("//speech[count(preceding-sibling::major-heading)=%d]", 
                seq_along(heading_recs))

# Get the text of the speech nodes
map(path, ~xml_text(xml_find_all(doc, .x))) %>% 
# Combine it with the id of the headings
  map2_df(xml_attr(heading_recs, "id"), 
          ~tibble(major_heading_id = .y, speech_text = .x))

这导致:

enter image description here