Nate
Nate

Reputation: 361

Fetching remote XML from URL using Dart / Flutter

I'm having trouble pulling XML data from a url. When I use http.get and print out the response.body - it looks like regular JSON. One of this issues is some of the XML nodes have attributes on them that I need to use. I'm still fairly new to Dart / Flutter so any help is REALLY appreciated. Here's my code for reference:

  String url = "url_to_data_remote_data";

  Future<DataModel> fetchData() async {
    final response = await http.get(url);

    if (response.statusCode == 200) 
      return DataModel.fromXML(response.body);
    } else {
      throw Exception('Failed to load post');
    }
  }

Upvotes: 1

Views: 2571

Answers (2)

Nate
Nate

Reputation: 361

Figured it out thanks to @Marc's comments; didn't know a hybrid service was a thing.

Essentially you need to set a header to accept xml. These are the lines of code that fixed my issue:

    Map<String, String> headers = {"Accept": "text/html,application/xml"};
    final response = await http.get(url, headers: headers);

Upvotes: 2

Mohamad Assem Nasser
Mohamad Assem Nasser

Reputation: 1109

You can use xml package to read the XML fetched. Then, you can use it however you like.

If you prefer working with JSON, which I recommend, use xml2json package to convert XML to JSON. handling JSON is easier in dart than handling XML.

Upvotes: 1

Related Questions