在 R 中解析 non-nested XML 标签
Parsing non-nested XML tags in R
我正在尝试使用出色的 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
不幸的是,因为标签没有嵌套,我不知道该怎么做!我有成功恢复相关信息的代码(见下文),但是将语音标签与它们各自的 major-headings 相匹配是我无法做到的。
我的直觉是,最好在标题标签处拆分 XML 文档,然后将每个文档作为单独的文档处理,但我找不到 [=15] 中的函数=] 可以让我这样做的软件包!
任何帮助都会很棒。
到目前为止我到达的地方:
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")
您可以按如下方式进行:
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))
这导致:
我正在尝试使用出色的 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
不幸的是,因为标签没有嵌套,我不知道该怎么做!我有成功恢复相关信息的代码(见下文),但是将语音标签与它们各自的 major-headings 相匹配是我无法做到的。
我的直觉是,最好在标题标签处拆分 XML 文档,然后将每个文档作为单独的文档处理,但我找不到 [=15] 中的函数=] 可以让我这样做的软件包!
任何帮助都会很棒。
到目前为止我到达的地方:
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")
您可以按如下方式进行:
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))
这导致: