XML

suggest change

Extensible Markup Language (XML) is a foundational format for SOAP web services, RSS/Atom feeds, SVG graphics, office documents, and platform manifests (such as Android's AndroidManifest.xml). In Dart, XML parsing, querying, and generation is provided by the official xml package.


Installing the xml Package

Add xml to your pubspec.yaml:

dependencies:
  xml: ^7.1.0

Run dart pub get to download the package.


Parsing and Querying XML

Use XmlDocument.parse() to parse raw XML strings into an in-memory document tree:

import 'package:xml/xml.dart';

void main() {
  const xmlContent = '''<?xml version="1.0" encoding="UTF-8"?>
<bookstore name="Downtown Books">
  <book id="b1" category="fiction">
    <title lang="en">The Great Gatsby</title>
    <author>F. Scott Fitzgerald</author>
    <price>12.99</price>
  </book>
  <book id="b2" category="science">
    <title lang="en">A Brief History of Time</title>
    <author>Stephen Hawking</author>
    <price>18.50</price>
  </book>
</bookstore>''';

  // Parse document
  final document = XmlDocument.parse(xmlContent);

  // Read root element and attributes
  final root = document.rootElement;
  print('Bookstore Name: ${root.getAttribute('name')}');

  // Find all <book> elements
  final books = document.findAllElements('book');

  for (final book in books) {
    final id = book.getAttribute('id');
    final category = book.getAttribute('category');
    final title = book.findElements('title').first.innerText;
    final author = book.findElements('author').first.innerText;
    final price = double.parse(book.findElements('price').first.innerText);

    print('[$id] "$title" by $author - \$$price ($category)');
  }
}

Traversing Child vs Descendant Elements


Building XML with XmlBuilder

The XmlBuilder class provides a declarative, fluent builder pattern for constructing valid, properly escaped XML documents:

import 'package:xml/xml.dart';

String generateRssFeed() {
  final builder = XmlBuilder();
  builder.processing('xml', 'version="1.0" encoding="UTF-8"');

  builder.element('rss', attributes: {'version': '2.0'}, nest: () {
    builder.element('channel', nest: () {
      builder.element('title', nest: 'Tech Blog Feed');
      builder.element('link', nest: 'https://example.com');
      builder.element('description', nest: 'Latest updates on Dart and Flutter');

      // Item 1
      builder.element('item', nest: () {
        builder.element('title', nest: 'Dart 3 Features & Patterns');
        builder.element('link', nest: 'https://example.com/posts/dart-3');
        builder.element('pubDate', nest: 'Sat, 17 Oct 2026 12:00:00 GMT');
        builder.element('guid', attributes: {'isPermaLink': 'true'}, nest: '101');
      });
    });
  });

  final xmlDoc = builder.buildDocument();

  // Pretty-print XML with 2-space indentation
  return xmlDoc.toXmlString(pretty: true, indent: '  ');
}

void main() {
  final rssXml = generateRssFeed();
  print(rssXml);
}

Error Handling

If the input contains invalid syntax, XmlDocument.parse() throws an XmlParserException. Mismatched or unclosed tags throw an XmlTagException. Both implement XmlFormatException, which carries the error location:

import 'package:xml/xml.dart';

void safeParse(String rawInput) {
  try {
    final doc = XmlDocument.parse(rawInput);
    print('Parsed successfully: ${doc.rootElement.name}');
  } on XmlFormatException catch (e) {
    print('Failed to parse XML: ${e.message}');
    print('Error at line ${e.line}, column ${e.column}');
  }
}

Modifying Existing XML Trees

You can mutate elements and attributes in an existing document:

import 'package:xml/xml.dart';

void main() {
  const xml = '<user id="42"><name>Alice</name><status>inactive</status></user>';
  final doc = XmlDocument.parse(xml);

  // Update attribute
  final user = doc.rootElement;
  user.setAttribute('verified', 'true');

  // Replace text node content
  final statusElement = user.findElements('status').first;
  statusElement.innerText = 'active';

  print(doc.toXmlString());
  // <user id="42" verified="true"><name>Alice</name><status>active</status></user>
}

Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents