我有一个链接向量,我想从中创建一个sitemap.xml文件(文件协议可从这里获得:http://www.sitemaps.org/protocol.html)
我理解sitemap.xml协议(它相当简单),但我不确定使用{xml}包的最聪明的方法是什么
一个简单的例子:
links <- c("http://r-statistics.com",
"http://www.r-statistics.com/on/r/",
"http://www.r-statistics.com/on/ubuntu/")
如何使用"链接"来构建sitemap.xml文件?
您想要的是这样的东西吗。(它使用httr
包来获得最后一个修改的位,并使用非常有用的whisker
包直接写入XML。)
require(whisker)
require(httr)
tpl <- '
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
{{#links}}
<url>
<loc>{{{loc}}}</loc>
<lastmod>{{{lastmod}}}</lastmod>
<changefreq>{{{changefreq}}}</changefreq>
<priority>{{{priority}}}</priority>
</url>
{{/links}}
</urlset>
'
links <- c("http://r-statistics.com", "http://www.r-statistics.com/on/r/", "http://www.r-statistics.com/on/ubuntu/")
map_links <- function(l) {
tmp <- GET(l)
d <- tmp$headers[['last-modified']]
list(loc=l,
lastmod=format(as.Date(d,format="%a, %d %b %Y %H:%M:%S")),
changefreq="monthly",
priority="0.8")
}
links <- lapply(links, map_links)
cat(whisker.render(tpl))
我无法使用@jverzani
的解决方案,因为我无法从cat输出创建有效的xml文件。因此,我创造了一个替代方案。
## Input a data.frame with 4 columns: loc, lastmod, changefreq, and priority
## This data.frame is named sm in the code below
library(XML)
doc <- newXMLDoc()
root <- newXMLNode("urlset", doc = doc)
temp <- newXMLNamespace(root, "http://www.sitemaps.org/schemas/sitemap/0.9")
temp <- newXMLNamespace(root, "http://www.google.com/schemas/sitemap-image/1.1", "image")
for (i in 1:nrow(sm))
{
urlNode <- newXMLNode("url", parent = root)
newXMLNode("loc", sm$loc[i], parent = urlNode)
newXMLNode("lastmod", sm$lastmod[i], parent = urlNode)
newXMLNode("changefreq", sm$changefreq[i], parent = urlNode)
newXMLNode("priority", sm$priority[i], parent = urlNode)
rm(i, urlNode)
}
saveXML(doc, file="sitemap.xml")
rm(doc, root, temp)
browseURL("sitemap.xml")