1

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');
    }
  }
3
  • 1
    so the body looks like JSON but you expect XML ? Is this a hybrid webservice that sends out the content depending on your ACCEPT http header? So perhaps it can do both JSON and XML depending on the client. Commented Nov 14, 2019 at 14:11
  • I'll try that, but in the event it's not a hybrid service - is there a way to consume XML in Dart / Flutter? Commented Nov 14, 2019 at 14:27
  • 1
    as to my knowledge http.get doesnt transform the content to something else Commented Nov 14, 2019 at 14:29

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Hi @Nate, I get Invalid argument(s): Unsupported scheme because the xml I get don't have the <xml> tag, can you help me?
I’ll look it over today and let you know what I can figure out
Sorry, I was trying with // and not http:// BUT when I get to my code on github I get "<" expected at 1:1
1

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.

1 Comment

the XML I'm using has attributes on that'll be used at a later time so xml2json may not suit the ticket requirements but I'll keep it on my radar.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.