java生成xml格式文件-提交sitemap

9 篇文章 1 订阅
6 篇文章 0 订阅

通过使用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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值