[英]How can I query xml with javascript?
javascript:
(async () => {
const rss = [
'https://reddit.com/r/news.rss',
/*
'https://www.upwork.com/ab/feed/jobs/rss?api_params=1&orgUid=424151849314844673&paging=0%3B10&q=title%3A%28cto%29&securityToken=925852acb79387c67d921519fd18fed25f501cc940c417db8a53c2ee9530a5a4c9fb27ac83bd44992aaa39d2509a1aa6e7053c4795d714657bc4ac744b268718&sort=recency&userUid=424151849306456064&user_location_match=1'
*/
];
let htm = '<section id="feed">';
rss.map(async feed => {
console.log('feed', feed);
let xml = '';
try {
const res = await fetch('https://api.allorigins.win/raw?url='+feed);
xml = await res.text();
console.log('xml', xml);
} catch(err) {
console.error(err);
return;
}
const node = new window.DOMParser().parseFromString(xml, "application/xml");
const items = [...node.evaluate('//entry', node, null, XPathResult.ANY_TYPE, null)];
console.log('items: ', items);
items.map(item => {
const link = item.evaluate('link', item);
const title = item.evaluate('title', item);
console.log('link: ', link.evaluate('@href', link));
console.log('title:', title.evalute('.', title));
htm += `
<div class="item">${link.evaluate('@href', link)} - ${title.evalute('.', title)}</div>
`;
});
});
htm += '</section>';
document.body.insertAdjacentHTML('beforeend', htm);
})();
我的title
和link
未定義,不知道為什么。
就提取title
和link
而言,我傾向於這樣做(這可能會進一步簡化):
const items = node.evaluate('//entry', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for(let i = 0; i < items.snapshotLength; i++) {
let entry = items.snapshotItem(i);
const link = node.evaluate('.//link/@href', entry, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
const title = node.evaluate('.//title', entry, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
console.log(link.snapshotItem(0).textContent);
console.log(title.snapshotItem(0).textContent);
}
output 應該是提要中 25 個條目中每個條目的標題和鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.