Javascript-форум (https://javascript.ru/forum/)
-   Элементы интерфейса (https://javascript.ru/forum/dom-window/)
-   -   распарсить xml (https://javascript.ru/forum/dom-window/78403-rasparsit-xml.html)

misha.korolcov 09.09.2019 01:15

распарсить xml
 
привет есть хмл https://api.privatbank.ua/p24api/pub...ange&coursid=5 на другом сайте надо получить и отобразить у себя не могу понять где ошибка
async function getDataFromCnbc() {

       
        const response = await                                                     
     fetch("https://corsproxy.glitch.me/https://api.privatbank.ua/p24api/pubinfo?exchange&coursid=5");
    const xml = await response.text();
    const xmlDocument = new DOMParser().parseFromString(xml, "text/xml");

    for(const node of xmlDocument.querySelectorAll("item")) {
        const details = document.createElement("details");
        const summary = document.createElement("summary");
        summary.append(node.querySelector("title"));        
        const description = document.createElement("description");
        description.innerHTML = node.querySelector("description").textContent;        
        const link = document.createElement("a");
        link.href = node.querySelector("link").textContent;
        link.textContent = "Read more";  
        details.append(summary, description, link);
        document.body.append(details);
    }

}

document.addEventListener("DOMContentLoaded", getDataFromCnbc);

рони 09.09.2019 01:47

misha.korolcov,
Пожалуйста, отформатируйте свой код!

Для этого его можно заключить в специальные теги: js/css/html и т.п., например:
[html run]
... минимальный код страницы с вашей проблемой
[/html]

О том, как вставить в сообщение исполняемый javascript и html-код, а также о дополнительных возможностях форматирования - читайте http://javascript.ru/formatting.

Malleys 09.09.2019 02:20

Цитата:

Сообщение от misha.korolcov
на другом сайте надо получить и отобразить у себя не могу понять где ошибка

На другом сайте другая структура xml. Соответственно вам нужна другая функция, которая будет разбирать другую структуру xml. Например так...
<style>

.buy, .sale {
	font: 1em system-ui;
	max-width: 20em;
	margin: 0 auto;
	display: flex;
}

.sale {
	margin-bottom: 1em;
}

.buy::before, .sale::before {
	opacity: 0.5;
	flex-basis: 5em;
	text-align: right;
	margin-right: 0.5em;
}

.buy::before {
	content: "Buy:";
}

.sale::before {
	content: "Sale:";
}

</style>
<script>

async function getDataFromPrivatBank() {
	const response = await fetch("https://corsproxy.glitch.me/https://api.privatbank.ua/p24api/pubinfo?exchange&coursid=5");
	const xmlDocument = new DOMParser().parseFromString(await response.text(), "text/xml");

	for(const node of xmlDocument.querySelectorAll("exchangerate")) {
		const buy = document.createElement("div");
		const sale = document.createElement("div");
		
		buy.className = "buy";
		sale.className = "sale";

		buy.innerHTML = `1 ${node.getAttribute("ccy")} = ${node.getAttribute("buy")} ${node.getAttribute("base_ccy")}`;
		sale.innerHTML = `1 ${node.getAttribute("ccy")} = ${node.getAttribute("sale")} ${node.getAttribute("base_ccy")}`;

		document.body.append(buy, sale);
	}
}

document.addEventListener("DOMContentLoaded", getDataFromPrivatBank);

</script>


Цитата:

Сообщение от рони
Пожалуйста, отформатируйте свой код!

Читайте отформатированный код тут... https://javascript.ru/forum/dom-wind...tml#post512512


Часовой пояс GMT +3, время: 04:53.