yuran soares
yuran soares

Reputation: 83

Flutter/dart: is there a way to convert json to xml?

There's a flutter package (xml2json) for converting xml to json, but not the other way around, json to xml. Is there a difficulty in making an algorithm that solves this? There are plenty of online json-xml converters, but no implementation for flutter

Upvotes: 1

Views: 1393

Answers (1)

yuran soares
yuran soares

Reputation: 83

I found that the xml package has a function for building xml, eg:

final builder = XmlBuilder();
builder.processing('xml', 'version="1.0"');
builder.element('bookshelf', nest: () {
  builder.element('book', nest: () {
    builder.element('title', nest: () {
      builder.attribute('lang', 'en');
      builder.text('Growing a Language');
    });
    builder.element('price', nest: 29.99);
  });
  builder.element('price', nest: '132.00');
});
final document = builder.buildDocument();

So, in my situation, I just had to instantiate the XmlBuilder(), start builder.processing('xml', 'version="1.0"');, cicle through my json file with foreach, and insert the json key/values to xmlbuilder tree, and finalize with builder.buildDocument()

Upvotes: 2

Related Questions