<p>XML站点地图</p><p>XML(可扩展标记语言)是一种用于存储和传输数据的标记语言,它具有易读、易解析的特点,在Web开发中,XML经常被用来存储和传输数据,特别是在构建站点地图时,本文将介绍如何使用PHP、Java和C++来生成XML站点地图。</p><p>PHP生成XML站点地图</p><p>我们需要创建一个PHP文件,lt;code>sitemap.php</code>,并在其中编写以下代码:</p><pre class="brush:php;toolbar:false">
<?php
header('Content-Type: application/xml; charset=UTF-8');
$urls = [
'https://www.example.com/page1',
'https://www.example.com/page2',
'https://www.example.com/page3',
];
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
foreach ($urls as $url) {
echo '<url>';
echo '<loc>' . htmlspecialchars($url) . '</loc>';
echo '<lastmod>' . date('Y-m-d H:i:s') . '</lastmod>';
echo '<changefreq>daily</changefreq>';
echo '<priority>1.0</priority>';
echo '</url>';
echo '</urlset>';
?></pre><p>在这个示例中,我们首先设置了响应的Content-Type为<code>application/xml; charset=UTF-8</code>,以便浏览器知道我们将发送XML数据,我们定义了一个包含URL的数组,并遍历该数组,为每个URL生成一个<code><url></code>元素,我们输出完整的XML站点地图。</p><p>Java生成XML站点地图</p><p>在Java中,我们可以使用JAXB库来生成XML站点地图,需要创建一个表示URL的类,lt;code>Url.java</code>:</p><pre class="brush:java;toolbar:false">
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Date;
@XmlRootElement(name = "url")
public class Url {
private String loc;
private Date lastmod;
private String changefreq;
private double priority;
@XmlElement(name = "loc")
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
@XmlElement(name = "lastmod")
public Date getLastmod() {
return lastmod;
}
public void setLastmod(Date lastmod) {
this.lastmod = lastmod;
}
@XmlElement(name = "changefreq")
public String getChangefreq() {
return changefreq;
}
public void setChangefreq(String changefreq) {
this.changefreq = changefreq;
}
@XmlElement(name = "priority")
public double getPriority() {
return priority;
}
public void setPriority(double priority) {
this.priority = priority;
}
}</pre><p>我们可以创建一个生成XML站点地图的方法,lt;code>generateSitemap.java</code>:</p><pre class="brush:java;toolbar:false">
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringWriter;
import java.time.LocalDateTime;
import java.time.format
还没有评论,来说两句吧...