前端需讀取靜態或動態生成的 XML 文件(如 Sitemap、配置數據、RSS 源),提取節點屬性與文本並在頁面渲染。
sitemap.xml)<?xml version="1.0" encoding="UTF-8"?>
<urlset>
<url>
<loc>https://example.com/page1</loc>
<lastmod>2023-01-01</lastmod>
</url>
<url>
<loc>https://example.com/page2</loc>
<lastmod>2023-01-02</lastmod>
</url>
</urlset>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery 讀取 XML 示例</title>
<style>
#showresult a { display: block; margin: 5px 0; color: #0066cc; }
</style>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
</head>
<body>
<div id="showresult">
<h2>站點地圖鏈接</h2>
<button id="read">點擊加載 XML</button>
</div>
<script>
$(function() {
$("#read").on("click", function() {
$.ajax({
type: "GET",
url: "sitemap.xml",
dataType: "xml", // 關鍵:指定返回類型為 XML
cache: false, // 防止 IE 緩存
success: function(xml) {
$(xml).find("url").each(function(i) {
if (i >= 10) return false; // 只顯示前 10 條
var loc = $(this).find("loc").text();
$("")
.attr("href", loc)
.text(loc)
.appendTo("#showresult");
});
},
error: function(xhr, status, err) {
console.error("XML 加載失敗:", status, err);
$("#showresult").append("加載失敗,請檢查路徑或格式
");
}
});
});
});
</script>
</body>
</html>
find()、attr()、text() 等方法遍歷。Access-Control-Allow-Origin 或使用代理。<ns:url>),需用 find("ns\\:url") 或註冊命名空間前綴。find("Url") 不會匹配 <url>。error: function(xhr, status, err) {
if (status === "parsererror") {
alert("XML 格式錯誤,請檢查文件語法");
} else if (xhr.status === 404) {
alert("XML 文件不存在");
} else {
alert("網絡錯誤: " + err);
}
}