0

I'm making and ajax request to an API that sends back XML format. With the following code the responseXml data gets printed out, but I don't know how I can parse it and access the data (like item.line or item.origTime).

Should I use JSON parser somehow or something else?

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 response

<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"/>
    ......
2
  • jxon is what you need. github.com/tyrasd/jxon Commented Jul 23, 2016 at 2:16
  • Jiang, could you pls write a code example? Commented Jul 23, 2016 at 9:03

1 Answer 1

1

here is the code exmaple, check the console output: 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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.