版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
通过使用org.jdom包的功能生成xml文件,提交搜索资源平台网站sitemap文件:
mavan:
<!-- https://mvnrepository.com/artifact/org.jdom/jdom -->
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom</artifactId>
<version>1.1.3</version>
</dependency>
生成代码:
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
public String createXML() throws Exception {
String xmlurl = "";
Element urlset = new Element("urlset");
Document document = new Document(urlset);
//文章链接的集合
List<String> listStr=new ArrayList<String>();
for(int i=1;i<200;i++){
listStr.add("http://www.citywy.com/"+i+".com");
}
int i=1;
for (String str : listStr) {
System.out.println(str+"生成中..."+i);
i++;
//<!--必填标签,这是具体某一个链接的定义入口,每一条数据都要用<url>和</url>包含在里面,这是必须的 -->
Element url = new Element("url");
//<!--必填,URL链接地址,长度不得超过256字节-->
Element loc = new Element("loc");
loc.setText(str);
url.addContent(loc);
//<!--可以不提交该标签,用来指定该链接的最后更新时间-->
Element lastmod = new Element("lastmod");
lastmod.setText("2018-06-06");
url.addContent(lastmod);
//<!--可以不提交该标签,用这个标签告诉此链接可能会出现的更新频率 -->
Element changefreq = new Element("changefreq");
changefreq.setText("daily");
url.addContent(changefreq);
//<!--可以不提交该标签,用来指定此链接相对于其他链接的优先权比值,此值定于0.0-1.0之间-->
Element priority = new Element("priority");
priority.setText("0.8");
url.addContent(priority);
urlset.addContent(url);
}
XMLOutputter XMLOut = new XMLOutputter();
try {
Format f = Format.getPrettyFormat();
f.setEncoding("UTF-8");//default=UTF-8
XMLOut.setFormat(f);
String path = "D://sitemap.xml";
XMLOut.output(document, new FileOutputStream(path));
} catch (Exception e) {
e.printStackTrace();
}
return xmlurl;
}
在D盘下生成的文件实例:
<?xml version="1.0" encoding="UTF-8"?>
<urlset>
<url>
<loc>http://www.citywy.com/1.com</loc>
<lastmod>2018-06-06</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>http://www.citywy.com/2.com</loc>
<lastmod>2018-06-06</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>http://www.citywy.com/3.com</loc>
<lastmod>2018-06-06</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
...
</urlset>