【发布时间】:2016-11-26 22:56:52
【问题描述】:
我正在向发送回 XML 格式的 API 发出 ajax 请求。使用以下代码打印出 responseXml 数据,但我不知道如何解析它并访问数据(如 item.line 或 item.origTime)。
我应该以某种方式或其他方式使用 JSON 解析器吗?
class App extends Component {
constructor(props) {
super(props);
this.state = { schedules: [] };
fetch('http://api.bart.gov/api/sched.aspx?cmd=stnsched&key=' + API_KEY + '&orig=12th&date=today')
.then((response) => response.text())
.then((responseXML) => {
this.setState({schedules: responseXML});
console.log(responseXML);
})
.catch((error) => {
console.log(error);
});
}
render () {
return (
<div>
<SelectList />
<TimeTable schedules={this.state.schedules} />
</div>
)
}
}
xml 响应
<root>
<uri>...</uri>
<date>7/22/2016</date>
<sched_num>39</sched_num>
<station>
<name>12th St. Oakland City Center</name>
<abbr>12TH</abbr>
<item line="ROUTE 7" trainHeadStation="MLBR" origTime="4:36 AM" destTime="5:21 AM" trainIdx="1" bikeflag="1"/>
<item line="ROUTE 2" trainHeadStation="PITT" origTime="4:37 AM" destTime="5:17 AM" trainIdx="1" bikeflag="1"/>
<item line="ROUTE 3" trainHeadStation="RICH" origTime="4:37 AM" destTime="5:00 AM" trainIdx="1" bikeflag="1"/>
<item line="ROUTE 1" trainHeadStation="SFIA" origTime="4:43 AM" destTime="5:28 AM" trainIdx="1" bikeflag="1"/>
......
【问题讨论】:
-
jxon 是您所需要的。 github.com/tyrasd/jxon
-
江,你能写一个代码例子吗?
标签: javascript json xml reactjs xml-parsing