js从xml response.text()获取数据

时间:2016-07-22 23:28:55

标签: javascript json xml reactjs xml-parsing

我正在向发送回XML格式的API发出ajax请求。使用以下代码打印出responseXml数据,但我不知道如何解析它并访问数据(如item.line或item.origTime)。

我应该以某种方式使用JSON解析器吗?

extern crate unicode_segmentation;

use unicode_segmentation::UnicodeSegmentation;

let s = "a̐éö̲\r\n";
let g = UnicodeSegmentation::graphemes(s, true).collect::<Vec<&str>>();
let b: &[_] = &["a̐", "é", "ö̲", "\r\n"];
assert_eq!(g, b);

xml回复

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>
    )
  }
}

1 个答案:

答案 0 :(得分:1)

这里是代码exmaple,检查控制台输出: https://jsfiddle.net/5rddp7tx/

const xmlStr=`
<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"/>
  </station>
</root>
`
var myObject = JXON.build(JXON.stringToXml(xmlStr));
console.log(myObject);
console.log(myObject.root.station.item[2].$line);