dart-flutter-xml-to-json-feature-image

Dart/Flutter – Convert XML to JSON using xml2json

In this Dart/Flutter tutorial, I will show you how to convert XML to JSON using xml2json package. You also know way to read XML file or get content from Url and parse XML to JSON object.

Related Post: Dart/Flutter – Convert/Parse JSON string, array into Object, List


Steps to convert XML to JSON

xml2json package provides methods to parse XML strings and transform the result tree into JSON. It supports 3 conventions:

  • Parker
  • Badgerfish
  • Google Data (GData)

Here are step by step we’re gonna do to convert XML to JSON:

  1. import xml2json package
  2. use Xml2Json.parse() function to parse XML String
  3. use Xml2Json.toParker(), toBadgerfish(), or toGData() to get JSON String from XML String
  4. parse JSON string to JSON object

Convert XML string to JSON

Assume that we have a String like this:

var xmlString = '''
    <tut>
      <id>123</id>
      <author>bezKoder</author>
      <title>Programming Tut#123</title>
      <publish_date>2020-3-16</publish_date>
      <description>Description for Tut#123</description>
    </tut>''';

We’re gonna use Xml2Json object to parse and transform XML String, then convert it to JSON using jsonDecode() function from dart:convert package.

import 'package:xml2json/xml2json.dart';
import 'dart:convert';

main() {
  final Xml2Json xml2Json = Xml2Json();

  var xmlString = '''
      <tut>
        <id>123</id>
        <author>bezKoder</author>
        <title>Programming Tut#123</title>
        <publish_date>2020-3-16</publish_date>
        <description>Description for Tut#123</description>
      </tut>''';

  xml2Json.parse(xmlString);
  var jsonString = xml2Json.toParker();
  // {"tut": {"id": "123", "author": "bezKoder", "title": "Programming Tut#123", "publish_date": "2020-3-16", "description": "Description for Tut#123"}}

  var data = jsonDecode(jsonString);
  // {tut: {id: 123, author: bezKoder, title: Programming Tut#123, publish_date: 2020-3-16, description: Description for Tut#123}}

  print(data['tut']);

Output:

{id: 123, author: bezKoder, title: Programming Tut#123, publish_date: 2020-3-16, description: Description for Tut#123}

It’s also work for XML String representation of a List:

var xmlString = '''<?xml version="1.0"?>
    <site>
      <tut>
        <id>tut_01</id>
        <author>bezKoder</author>
        <title>Programming Tut#1</title>
        <publish_date>2020-8-21</publish_date>
        <description>Tut#1 Description</description>
      </tut>
      <tut>
        <id>tut_02</id>
        <author>zKoder</author>
        <title>Software Dev Tut#2</title>
        <publish_date>2020-12-18</publish_date>
        <description>Tut#2 Description</description>
      </tut>
    </site>''';

xml2Json.parse(xmlString);
var jsonString = xml2Json.toParker();
var data = jsonDecode(jsonString);

var tutList = data['site']['tut'];
for (var item in tutList) {
  print(item);
}

Output:

{id: tut_01, author: bezKoder, title: Programming Tut#1, publish_date: 2020-8-21, description: Tut#1 Description}
{id: tut_02, author: zKoder, title: Software Dev Tut#2, publish_date: 2020-12-18, description: Tut#2 Description}

Read XML file in Dart/Flutter

Now, how about the content inside bezkoder.xml?

Before converting it to JSON, we need to read XML content in the file as a String.
Let’s create a function with the help of dart:io library.

import 'dart:io';
import 'package:xml2json/xml2json.dart';
import 'dart:convert';

getJsonFromXMLFile(path) async {
  final Xml2Json xml2Json = Xml2Json();

  try {
    var content = await File(path).readAsString();
    xml2Json.parse(content);

    var jsonString = xml2Json.toParker();
    return jsonDecode(jsonString);
  } catch (e) {
    print(e);
  }
}

You can see that we create a File object from the path and read it by readAsString() method. Then we parse XML and convert it to JSON object using an instance of Xml2Json.

Now we can use the function like following code:

var data = await getJsonFromXMLFile('src/bezkoder.xml');
// {articles: {post: [{id: tut_01, author: bezKoder, title: Programming Tut#1, publish_date: 2020-8-21, description: Tut#1 Description}, {id: tut_02, author: zKoder, title: Software Dev Tut#2, publish_date: 2020-12-18, description: Tut#2 Description}]}}

var tutList = data['articles']['post'];
for (var item in tutList) {
  print(item);
}

Output:

{id: tut_01, author: bezKoder, title: Programming Tut#1, publish_date: 2020-8-21, description: Tut#1 Description}
{id: tut_02, author: zKoder, title: Software Dev Tut#2, publish_date: 2020-12-18, description: Tut#2 Description}

Convert Url that contains XML to JSON

Now there is an XML file at the url: https://bezkoder.com/sample/bezkoder.xml.

Firstly, we have to get the content in the url as String format. So we create a function to do this.

import 'package:xml2json/xml2json.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

getJsonFromXMLUrl(String url) async {
  final Xml2Json xml2Json = Xml2Json();

  try {
    var response = await http.get(url);
    xml2Json.parse(response.body);

    var jsonString = xml2Json.toParker();
    return jsonDecode(jsonString);
  } catch (e) {
    print(e);
  }
}

In the function above, we use http package to send HTTP GET request to the endpoint. Once we get the String, continue to parse and decode it to JSON.

And this is how we use the async function with await.

var data = await getJsonFromXMLFile('src/bezkoder.xml');

var tutList = data['articles']['post'];
for (var item in tutList) {
  print(item);
}

Output:

{id: tut_01, author: bezKoder, title: Programming Tut#1, publish_date: 2020-8-21, description: Tut#1 Description}
{id: tut_02, author: zKoder, title: Software Dev Tut#2, publish_date: 2020-12-18, description: Tut#2 Description}

Conclusion

Today we’ve known how to convert/parse XML to JSON object using xml2json package. Remember that there are 3 conventions but we only use one: Parker with toParker() function. You can try others which results will have a little difference.

Happy Learning! See you again.

Further Reading

Leave a Reply

Your email address will not be published. Required fields are marked *