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 Posts:
Dart/Flutter – Convert/Parse JSON string, array into Object, List
Dart/Flutter – Sort list of Objects

Dart/Flutter Constructors tutorial with examples
Dart/Flutter String Methods & Operators tutorial with examples
Dart/Flutter Future Tutorial with Examples
Dart/Flutter List Tutorial with Examples
Dart/Flutter Map Tutorial with Examples


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

Dart/Flutter Constructors tutorial with examples
Dart/Flutter String Methods & Operators tutorial with examples
Dart/Flutter Future Tutorial with Examples
Dart/Flutter List Tutorial with Examples
Dart/Flutter Map Tutorial with Examples
Dart/Flutter – Sort list of Objects

3 thoughts to “Dart/Flutter – Convert XML to JSON using xml2json”

Comments are closed to reduce spam. If you have any question, please send me an email.