例えば以下のようなXMLがあるとします。
<?xml version="1.0" encoding="UTF-8"?> <urlset> <url> <loc>https://www.kipure.com/</loc> <lastmod>2020-03-31T15:00:04+00:00</lastmod> <priority>1.00</priority> </url> <url> <loc>https://www.kipure.com/category/</loc> <lastmod>2020-03-31T15:00:04+00:00</lastmod> <priority>0.80</priority> </url> <url> <loc>https://www.kipure.com/search/</loc> <lastmod>2020-03-31T15:00:04+00:00</lastmod> <priority>0.80</priority> </url> </urlset>
上記のXMLは一般的なsitemap.xmlのフォーマットです。
例えばこの中のURLの情報だけでリンクが作りたいときのサンプルを解説します。
同じ階層に、XMLとHTMLを置いてHTML以下のような記述をします。
JSの部分
//XMLのファイルのパス const xml = "sitemap.xml"; $(function(){ $.ajax({ type: "GET", url: xml, dataType: "xml", success: function(xml){ array_elements = []; //<loc>タグを複数探してthisに格納 $(xml).find('loc').each(function(){ //<loc>この部分</loc>を抽出 loc = $(this).html(); //<loc hoge="fuga">hogeを抽出するなら $(this).attr("hoge"); //配列に格納 array_elements.push(loc); }); array_elements.sort(); view(array_elements); } }); }); //HTMLに書き出す部分 function view(arr){ for (var i = 0; i < arr.length; i++) { html = '<div class="loc"><a target="_blank" href="'+arr[i]+'">'+arr[i]+'</a></div>'; $("#demo_result").append(html); } }
jQueryの読み込みが前提です。
HTMLには以下のような記述のみです。
<div id="demo_result"></div>
実行すると
以上ののようなリンクが作成できます。
つまり、上記のXMLから以下のようなHTMLをJSで生成しています。
<div class="loc"><a href="https://www.kipure.com/" target="blank">https://www.kipure.com/</a></div> <div class="loc"><a href="https://www.kipure.com/category/" target="blank">https://www.kipure.com/category/</a></div> <div class="loc"><a href="https://www.kipure.com/search/" target="blank">https://www.kipure.com/search/</a></div>
この記述ではローカルに置いただけでは実行できません。
ローカルサーバを立ち上げるか、サーバ上でないとXMLの読み込みに失敗します。