[英]How to access attributes on xml feed
I am trying to parse data from an xml file in my React JS app, but it seems to return a full xml object comprising of 25 or so 'cube' elements. 我正在尝试从我的React JS应用程序中的xml文件中解析数据,但是它似乎返回包含25个左右“多维数据集”元素的完整xml对象。 I'm interested in accessing the 'currency' and 'rate' attribute of each cube, and output each of these inside of a dropdown. 我对访问每个多维数据集的'currency'和'rate'属性感兴趣,并在下拉菜单中输出它们。 Is there a way of looping over all the cubes and somehow targeting these? 有没有一种方法可以遍历所有多维数据集并以某种方式针对这些多维数据集? I'm trying to build a currency converter that automatically converts a price entered by the user. 我正在尝试建立一个货币转换器,该转换器可以自动转换用户输入的价格。
My code: 我的代码:
import React, { Component } from 'react';
import "../../App.css"
class Countries extends Component {
constructor() {
super();
this.state = {
countrycodes: [],
exchangerates: []
};
}
componentDidMount(){
fetch('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml')
.then(response => response.text())
.then(str => (new window.DOMParser()).parseFromString(str, "text/xml"))
.then(data => {
const cubes = data.getElementsByTagName("Cube")
for( const element of cubes) {
if (!element.getAttribute('currency')) {
continue;
}
let countrycodes = element.getAttribute('currency')
let exchangerates = element.getAttribute('rate')
this.setState({
countrycodes: countrycodes,
exchangerates: exchangerates
})
}
});
}
render() {
return (
<div className="container2">
<div className="container1">
<select>{this.state.countrycodes.map((country) => {
<option>{country}</option>})
}
</select>
</div>
</div>
)
}
}
export default Countries;
Thanks, 谢谢,
Robert 罗伯特
Use getAttribute : 使用getAttribute :
class Countries extends React.Component {
constructor() {
super();
this.state = {
countryCodes: []
};
}
componentDidMount(){
fetch({url: 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'})
.then(response => response.text())
.then(str => (new window.DOMParser()).parseFromString(str, "text/xml"))
.then(data => {
const countryCodes = [];
const cubes = data.getElementsByTagName("Cube");
for (const element of cubes) {
if (!element.getAttribute('currency')) {
// skip cube with no currency
continue;
}
countryCodes.push({
currency:element.getAttribute('currency'),
rate: element.getAttribute('rate')
});
}
this.setState({countryCodes});
});
}
render() {
const options = this.state.countryCodes.map(
({currency, rate}) => (<option value={rate}>{currency} - {rate}</option>));
return (
<div className="container2">
<div className="container1">
<select>
{options}
</select>
</div>
</div>
)
}
}
To check you can open http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml and run fetch(...)
directly in browser's console: 要进行检查,您可以打开http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml并直接在浏览器的控制台中运行fetch(...)
:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.