将XML文本读入小标题

时间:2019-05-24 23:11:49

标签: r xml tidyverse

我想要这样的xml文件(我称其为“ 2019-05-24.xml”):

<file>
    <header>
        <filename>2019-05-24</filename>
    </header>
    <body>
        <div type="article">
            <head>First test article</head>
            <p>Some information.</p>
            <p>Some other information.</p>
        </div>
        <div type="section" feature="essay">
            <head>Test essay</head>
            <p>An argument.</p>
            <p>Supporting evidence.</p>
        </div>
    </body>
</file>

将其变成这样的小玩意

# A tibble: 3 x 6
  filename        seq type    feature head       text                                                                    
  <chr>         <int> <chr>   <chr>   <chr>      <chr>                                                                  
1 2019-05-24.xml    1 article NA      First test "Some information. Other information. Yet…
2 2019-05-24.xml    2 section essay   Test essay "An argument. Supporting evidence."                              
3 2019-05-24.xml    3 index   NA      NA         "Article.....1 Essay....2"      

这使我一路走来

sample <- "2019-05-24.xml"

extract_data <- function(x){
  divs <- x %>% 
    read_xml() %>%
    xml_child(2) %>%
    xml_find_all(".//div")
  text <- xml_text(divs)
  type <- xml_attr(divs, "type")
  feature <- xml_attr(divs, "feature")
  seq <- seq_along(divs)
  test_tibble <- tibble(filename = x, seq = seq, type = type, feature = feature, text = text)
}

lapply(sample, extract_data)

不幸的是,结果将headp文本串联在一起。

# A tibble: 3 x 5
  filename       seq type    feature text                                                       
  <chr>        <int> <chr>   <chr>   <chr>                                                      
1 2019-05-24.…     1 article NA      "First test articleSome information.\n            Other in…
2 2019-05-24.…     2 section essay   Test essayAn argument.Supporting evidence.                 
3 2019-05-24.…     3 index   NA      Article.....1Essay....2                                    

问题1:头

如果我以提取文本的相同方式提取head

head <- sample %>% 
  read_xml() %>%
  xml_child(2) %>%
  xml_find_all(".//div/head//text()")

我收到错误消息是因为第三个div不包含head

Error: Tibble columns must have consistent lengths, only values of length one are recycled:
* Length 2: Column `head`
* Length 3: Columns `seq`, `type`, `feature`

如果NA中没有head,我是否可以使该函数返回div

问题2:在div中阅读文本

我只想阅读divs列表中三个项目或节点中的每个文本。我可以在每个节点上单独进行类似text <- divs %>% xml_children %>% xml_text()的操作(该操作返回整个文件中的每个子级)吗?我尝试了各种apply()变体。我认为我在XPath和xml_find_allxml_text上做错了,但我无法弄清楚。

1 个答案:

答案 0 :(得分:0)

要解决您的问题,需要分别解析每个div,然后创建数据帧列表,然后将所有内容绑定在一起。

await