1
いくつかのRmarkdown-Filesを解析するために、xml2
-packageを実験し始めています。今、私は構造化された方法でhtmlコメントを解析する際に、またセクション間の情報を解析する際に非常に込み入っています(####
など)xml2を解析するhtml-comments
コメントの内容にアクセスしようとしています。
library(xml2)
library(magrittr)
# html-output as created by rmarkdown
x <- xml2::read_xml("
<div id='header-level-1' class='section level1'>
<h1>Header Level 1</h1>
<!-- This is a comment, which I want to parse -->
<div id='header-level-4-1' class='section level4'>
<h4>Header Level 4 (1)</h4>
<!-- parse me 4 (1) -->
<p>Hello!</p>
</div>
<div id='header-level-4-2' class='section level4'>
<h4>Header Level 4 (2)</h4>
<!-- parse me 4 (2) -->
<p>How are you?</p>
<pre class='r'><code>print("Hello World")</code></pre>
</div>
</div>
")
# inspecting the structure, {comments} are present as a structural element
x %>%
html_structure()
#> <div#header-level-1 .section.level1>
#> <h1>
#> {text}
#> {comment}
#> <div#header-level-4-1 .section.level4>
#> <h4>
#> {text}
#> {comment}
#> <p>
#> {text}
#> <div#header-level-4-2 .section.level4>
#> <h4>
#> {text}
#> {comment}
#> <p>
#> {text}
#> <pre.r>
#> <code>
#> {text}
# first attempt to acess content of comments
x %>%
xml_find_all("//div") %>%
sub("^.*<!-- ", "", .) %>%
sub(" -->.*$", "", .)
#> [1] "parse me 4 (2)" "parse me 4 (1)" "parse me 4 (2)"
私は確信して、より良い方法はありますか?理想的には、私はコメントを得て、階層構造(これらのコメントは例えばこれらのコメントに属していた)を保持する。