XML
suggest changeExtensible 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
document.findAllElements('tag'): Recursively searches all descendants anywhere in the subtree.element.findElements('tag'): Looks only at direct immediate children of the element.element.getAttribute('attr'): Safely retrieves an attribute value (or returnsnullif not present).
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
- Use
XmlBuilderrather than manual string concatenation: Manually constructing XML with string interpolation risks invalid syntax and XML injection vulnerabilities when text contains<or&. - Use
getAttribute()with null-coalescing: Attributes are optional in XML; always guard againstnullreturns. - Catch
XmlFormatException: Wrap parsing logic intry-catchblocks when handling untrusted user or remote network inputs. - Format with
pretty: truefor debugging: Keep production network payloads compact withtoXmlString(), and usepretty: trueonly when writing configuration files or logging.