【问题标题】:How to Parse XML using axios in react js如何在 React js 中使用 axios 解析 XML
【发布时间】:2021-12-31 13:18:18
【问题描述】:
【问题讨论】:
标签:
javascript
node.js
reactjs
xml
rss
【解决方案1】:
抱歉,我不是 React 开发人员,这是你在 vanilla JS 中的做法。
<html>
<body>
<script type='text/javascript'>
let RSS_URL = "https://anchor.fm/s/75abc654/podcast/rss"
fetch(RSS_URL)
.then(response => response.text())
.then(str => new window.DOMParser().parseFromString(str, "text/xml"))
.then(data => {
console.log(data);
const items = data.querySelectorAll("item");
let html = `<table>`;
items.forEach(el => {
let title = null;
let link = null;
let description = null;
let image = null;
// since we can't use querySelector to locate itunes:image namespaces, iterate through all child nodes, and pick off what we want.
let itemNodes = el.querySelectorAll( "*" );
itemNodes.forEach( item => {
switch( item.nodeName ) {
case "title":
title = item.textContent;
break;
case "description":
description = item.textContent;
break;
case "link":
link = item.innerHTML;
break;
case "itunes:image":
image = item.getAttribute( "href" );
break;
}
});
// Build the HTML
html += `
<tr>
<td>
<a href="${link}" target="_blank" rel="noopener">${title}</a>
</td>
<td>
<img src="${image}" width='100px'/>
</td>
<td>
${description}
</td>
</tr>
`;
});
html += "</table>";
document.body.insertAdjacentHTML("beforeend", html);
});
</script>
</body>
</html>