我刚刚意识到,您想替换所有子节点。下面是实现这一点的代码。
lapply
要打开每个文件,请解析XML代码,删除
head
script
带参数的元素
src
去吧。
替换所有子节点
library(XML)
files <- list.files(full.names = T, pattern = "*.html")
lapply(files, function(f) {
content <- xmlInternalTreeParse(f, isHTML = T)
# get head node
headNode <- getNodeSet(content, path = "//head")
# remove all child nodes
do.call(removeChildren, args = list(kids = names(xmlChildren(headNode[[1]])), node = headNode[[1]]))
# create new nodes
newNode <- newXMLNode("script", attrs = list(src = "myScript.js"))
# add new nodes
addChildren(headNode[[1]], newNode)
saveXML(doc = content, file = f)
})
library(XML)
files <- list.files(full.names = T, pattern = "*.html")
lapply(files, function(f) {
content <- xmlInternalTreeParse(f, isHTML = T)
headNode <- getNodeSet(content, path = "//head")
newNode <- newXMLNode("script", attrs = list(src = "myScript.js"))
addChildren(headNode[[1]], newNode)
saveXML(doc = content, file = f)
})