Working with XML in Dart and Flutter

Dart offers dart:io package for reading file. To traverse an XML file, we need more than that package.

Table of Contents

xml

xml is a Dart library for parsing, traversing, querying, transforming and building XML documents.

var xmlString = '<?xml version="1.0"?>
<root>
  <item>
    <name>Zander Upton</name>
    <info>
      <title>Dr.</title>
      <age>42</age>
      <phone>573.858.4705</phone>
      <email>[email protected]</email>
    </info>
  </item>
  <item>
    <name>Kurtis Maggio</name>
    <info>
      <title>Prof.</title>
      <age>53</age>
      <phone>381-994-9264 x895</phone>
      <email>[email protected]</email>
    </info>
  </item>  
</root>';

//string to XML document
final document = XmlDocument.parse(xmlString);
//convert document to string
var xmlStr = document.toXmlString(pretty: true, indent: '\t');

//traverse
final textual = document.descendants
  .where((node) => node is XmlText && !node.text.trim().isEmpty)
  .join('\n');
print(textual);

//get all item nodes
final items = document.findAllElements('item');

final total = document.findAllElements('item')
    .map((node) => double.parse(node.findElements('age').single.text))
    .reduce((a, b) => a + b);
print(total);

xml_parser

This is an unopinionated XML parser that can read, traverse, and write XML documents.

XmlDocument xmlDocument = XmlDocument.fromString(xmlString);

//get document info
print(xmlDocument.xmlDeclaration.version); 
print(xmlDocument.xmlDeclaration.encoding);
print(xmlDocument.xmlDeclaration.standalone);
print(xmlDocument.doctype.element); 
print(xmlDocument.doctype.externalDtdUri);
print(xmlDocument.root.children.length);

//extract nodes
List<XmlNode> nodes = XmlNode.parseString(
  xmlString,
  returnNodesOfType: <Type>[XmlDeclaration, XmlDoctype, XmlElement],
);

for (XmlNode child in document.children) {
  if (child is XmlDeclaration) {
    print(child.version); // 1.0
  } else if (child is XmlDoctype) {
    print(child.externalDtdName); // rootDtd
  } else if (child is XmlElement) {
    print(child.name); // root
  }
}

xml2json

Like the name suggests, this package convert an XML string to JSON. It supports Badgerfish, GData and Parker conversions.

final converter = Xml2Json();
converter.parse(xmlString); //xmlString is a string in example above

//other conversions
converter.toBadgerfish();
converter.toGData();
converter.toParker();

Leave a Comment

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


Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close