r - R中的xml,删除段落但保留xml类
问题描述
我正在尝试从 R 中的 XML 文档中删除一些段落,但我想保留 XML 结构/类。这是一些示例文本和我失败的尝试:
library(xml2)
text = read_xml("<paper> <caption><p>The main title</p> <p>A sub title</p></caption> <p>The opening paragraph.</p> </paper>")
xml_find_all(text, './/caption//p') %>% xml_remove() # deletes text
xml_find_all(text, './/caption//p') %>% xml_text() # removes paragraphs but also XML structure
这是我想要结束的内容(只是删除了标题中的段落):
ideal_text = read_xml("<paper> <caption>The main title A sub title</caption> <p>The opening paragraph.</p> </paper>")
ideal_text
解决方案
看起来这需要多个步骤。找到节点,复制文本,删除节点的内容,然后更新。
library(xml2)
library(magrittr)
text = read_xml("<paper> <caption><p>The main title</p> <p>A sub title</p></caption> <p>The opening paragraph.</p> </paper>")
# find the caption
caption <- xml_find_all(text, './/caption')
#store existing text
replacemement<- caption %>% xml_find_all( './/p') %>% xml_text() %>% paste(collapse = " ")
#remove the desired text
caption %>% xml_find_all( './/p') %>% xml_remove()
#replace the caption
xml_text(caption) <- replacemement
text #test
{xml_document}
<paper>
[1] <caption>The main title A sub title</caption>
[2] <p>The opening paragraph.</p>
您很可能需要获取字幕节点的向量/列表,然后通过循环逐个遍历它们。
推荐阅读
- python - 无法使用 Fast CGI (wfastcgi) 在 IIS 上托管 django。在浏览器中出现 500 错误
- reactjs - 如何将建议框添加到 React 中的文本输入
- javascript - 如何在外部和跨源 iframe 中获取光标位置和光标事件?
- javascript - 添加新行时的 DataTable 警告消息
- java - 使用 maven 项目的 GitHub 页面
- java - Java Swing and Concurrency - 在动作发生之前休眠请求
- php - 根据两列的 $_POST 值将列值更新为 NULL?
- c# - 使用 Restsharp 发布 json 文件
- sql - 如何计算不同的值以排除值?
- ios - 如何设置 UIDatePicker 以显示今天及以后的日期?