ZetCode

Dart XML

last modified October 18, 2026

In this article we show how to work with XML data in Dart language. We read, query, modify, and build XML data.

Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. XML is often used for application configuration, data storage and exchange.

XML is similar to HTML, but does not have predefined tags; we can design our own tags.

In Dart, we use the package:xml/xml.dart to work with XML.

$ dart pub add xml

We add the package to the project structure.

Dart XML simple example

In the first example, we read XML data from a string with XmlDocument.parse. The method returns an XmlDocument for the given input string.

simple.dart
import 'package:xml/xml.dart';

void main() {
  const data = '''<?xml version="1.0" encoding="utf-8"?>
<value>6</value>''';

  final xdoc = XmlDocument.parse(data);

  print(xdoc);
  print('------------------');
  print(xdoc.findAllElements('value').first);
  print(xdoc.rootElement.innerText);
}

The example parses the XML data and prints the whole document to the terminal. We also find the value element and print it, and then we print the text of the root element with innerText. Invalid XML throws an XmlParserException.

$ dart simple.dart
<?xml version="1.0" encoding="utf-8"?>
<value>6</value>
------------------
<value>6</value>
6

Dart read XML from file

In the next example, we read XML data from a file.

books.xml
<?xml version="1.0" encoding="utf-8"?>
<bookstore>
    <book genre="Science Fiction">
        <title>Dune</title>
        <author>Frank Herbert</author>
        <price>8.99</price>
    </book>
    <book genre="Novel">
        <title>Old Goriot</title>
        <author>Honoré de Balzac</author>
        <price>9.0</price>
    </book>
</bookstore>

We have this books.xml file.

read_file.dart
import 'dart:io';

import 'package:xml/xml.dart';

void main() {
  final file = File('books.xml');
  final data = file.readAsStringSync();
  final xdoc = XmlDocument.parse(data);

  print(xdoc);
}

We import the dart:io package and read the contents of the file with the readAsStringSync method of File.

final xdoc = XmlDocument.parse(data);

We parse the data into an XML document with XmlDocument.parse. Printing the document gives back the original text, including the whitespace.

$ dart read_file.dart
<?xml version="1.0" encoding="utf-8"?>
<bookstore>
    <book genre="Science Fiction">
        <title>Dune</title>
        <author>Frank Herbert</author>
        <price>8.99</price>
    </book>
    <book genre="Novel">
        <title>Old Goriot</title>
        <author>Honoré de Balzac</author>
        <price>9.0</price>
    </book>
</bookstore>

Dart XML elements and attributes

The rootElement property is the top element of the document. The childElements property lists the child elements, ignoring text nodes, getAttribute reads an attribute, and innerText returns the concatenated text of the node and its descendants.

elements.dart
import 'dart:io';

import 'package:xml/xml.dart';

void main() {
  final xdoc = XmlDocument.parse(File('books.xml').readAsStringSync());
  final root = xdoc.rootElement;

  print(root.name.local);

  for (final book in root.childElements) {
    final genre = book.getAttribute('genre');
    final title = book.getElement('title')!.innerText;
    final price = double.parse(book.getElement('price')!.innerText);

    print('$title ($genre): $price');
  }
}

We iterate over the book elements. The getElement method returns the first child element with the given name, or null. The price is converted to a number, because XML contains only text.

$ dart elements.dart
bookstore
Dune (Science Fiction): 8.99
Old Goriot (Novel): 9.0

Dart XML where

The where method returns a lazy iterable from the document which satisfies the given predicate.

where_fun.dart
import 'dart:io';

import 'package:xml/xml.dart';

void main() {
  final xdoc = XmlDocument.parse(File('books.xml').readAsStringSync());

  xdoc.descendants
      .where((e) => e.getAttribute('genre') == 'Novel')
      .forEach(print);
}

We loop through the descendants and get all elements whose genre attribute is equal to "Novel".

$ dart where_fun.dart
<book genre="Novel">
        <title>Old Goriot</title>
        <author>Honoré de Balzac</author>
        <price>9.0</price>
    </book>

Dart XML findAllElements

The findAllElements method returns a lazy iterable of the recursive child elements in document order with the specified tag name.

find_all.dart
import 'dart:io';

import 'package:xml/xml.dart';

void main() {
  final xdoc = XmlDocument.parse(File('books.xml').readAsStringSync());
  final books = xdoc.findAllElements('book');

  for (final book in books) {
    print(book.innerText.trim().replaceAll(RegExp(r'\s+'), ' '));
  }

  print('----------------');

  for (final book in books) {
    print(book.findAllElements('title').single.innerText);
  }
}

In the example, we find all the text data of the book elements and then all the titles. The whitespace between the elements is collapsed with a regular expression.

$ dart find_all.dart
Dune Frank Herbert 8.99
Old Goriot Honoré de Balzac 9.0
----------------
Dune
Old Goriot

Dart XML XPath

The xpath.dart library of the package adds XPath queries to the nodes. XPath is a compact language for selecting nodes in an XML document.

xpath.dart
import 'dart:io';

import 'package:xml/xml.dart';
import 'package:xml/xpath.dart';

void main() {
  final xdoc = XmlDocument.parse(File('books.xml').readAsStringSync());

  print(xdoc.xpath('/bookstore/book/title').map((e) => e.innerText).toList());
  print(xdoc.xpath('//book[@genre="Novel"]/author/text()').join());
  print(xdoc.xpath('//book[price > 8.99]/title').single.innerText);
  print(xdoc.xpath('//book/@genre').map((e) => e.value).toList());
}

The first query selects all titles; the second finds the author of the novels using a predicate on the attribute; the third compares the price (converted to a number by XPath); and the last one returns the values of the genre attributes.

$ dart xpath.dart
[Dune, Old Goriot]
Honoré de Balzac
Old Goriot
[Science Fiction, Novel]

Dart XML modify document

The nodes of a parsed document are mutable. We can change attributes and text, and append or remove children. The toXmlString method serializes the result, optionally with indentation.

modify.dart
import 'package:xml/xml.dart';

void main() {
  final xdoc = XmlDocument.parse('<list><item>one</item><item>two</item></list>');
  final list = xdoc.rootElement;

  list.setAttribute('count', '3');

  list.children.add(XmlElement(XmlName('item'), [], [XmlText('three')]));

  list.firstElementChild!.innerText = 'ONE';
  list.getElement('item')!.setAttribute('first', 'yes');

  list.children.removeAt(1);

  print(xdoc.toXmlString(pretty: true));
}

We add an attribute, append a new item element, change the text and attribute of the first item, and remove the second child. Note that the children list contains all nodes, so the child at index 1 is the second item, since this compact document has no whitespace text nodes.

$ dart modify.dart
<list count="3">
  <item first="yes">ONE</item>
  <item>three</item>
</list>

Dart build XML document

XML documents can be built with XmlBuilder.

builder.dart
import 'package:xml/xml.dart';

void main() {
  final xdoc = buildXml();
  print(xdoc.toXmlString(pretty: true, indent: '  '));
}

XmlDocument buildXml() {
  final builder = XmlBuilder();

  builder.processing('xml', 'version="1.0" encoding="utf-8"');
  builder.element('bookstore', nest: () {
    builder.element('book', nest: () {
      builder.attribute('genre', 'Science Fiction');
      builder.element('title', nest: 'Dune');
      builder.element('author', nest: 'Frank Herbert');
      builder.element('price', nest: 8.99);
    });
    builder.element('book', nest: () {
      builder.attribute('genre', 'Novel');
      builder.element('title', nest: 'Old Goriot');
      builder.element('author', nest: 'Honoré de Balzac');
      builder.element('price', nest: 9.0);
    });
  });

  return builder.buildDocument();
}

The example creates a bookstore XML document.

final builder = XmlBuilder();

We create an instance of the XmlBuilder.

builder.element('bookstore', nest: () {
  builder.element('book', nest: () {
    builder.attribute('genre', 'Science Fiction');
    builder.element('title', nest: 'Dune');
    ...
  });
});

A new element is created with element. Nested elements and attributes are created inside the nest callback; a value that is not a function, such as a string or a number, becomes the text of the element.

return builder.buildDocument();

The document is finalized with buildDocument. With pretty: true, the string is indented.

$ dart builder.dart
<?xml version="1.0" encoding="utf-8"?>
<bookstore>
  <book genre="Science Fiction">
    <title>Dune</title>
    <author>Frank Herbert</author>
    <price>8.99</price>
  </book>
  <book genre="Novel">
    <title>Old Goriot</title>
    <author>Honoré de Balzac</author>
    <price>9.0</price>
  </book>
</bookstore>

Dart XML escaping

The package escapes the special characters <, & and quotes when the document is serialized, so we never have to do it manually. When the text is read back, the original characters are restored.

escape.dart
import 'package:xml/xml.dart';

void main() {
  final builder = XmlBuilder();
  builder.element('note', nest: () {
    builder.attribute('title', 'Q&A "session"');
    builder.text('if a < b && b > c');
  });

  final xdoc = builder.buildDocument();
  print(xdoc);
  print(xdoc.rootElement.innerText);
}

The serialized form contains entity references, while innerText returns the plain text.

$ dart escape.dart
<note title="Q&amp;A &quot;session&quot;">if a &lt; b &amp;&amp; b > c</note>
if a < b && b > c

Source

Dart xml library documentation

In this article we have worked with XML data in Dart.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all Dart tutorials.