How to Use the Converter
- Paste or Upload: Paste your raw XML payload into the input editor, or click Upload .xml File to load an existing file from your device.
- Validate Your Structure: Ensure your XML is well-formed with matching tags. If your XML contains formatting errors or broken entities, run it through an XML Validator first.
- Convert: Click Convert To Dart to process the markup.
- Copy or Download: Use Copy To Clipboard to paste the code directly into your IDE, or click Download .Dart to save a
.dartfile for your project.
Example: XML Input to Dart Model
Here is an example demonstrating how an XML document is transformed into a structured Dart model.
Input XML
XML
<catalog>
<product id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<in_stock>true</in_stock>
</product>
</catalog>
Generated Dart Output
Dart
class Catalog {
final List<Product> products;
Catalog({required this.products});
factory Catalog.fromXmlElement(XmlElement element) {
return Catalog(
products: element.findElements('product').map((e) => Product.fromXmlElement(e)).toList(),
);
}
}
class Product {
final String id;
final String? author;
final String? title;
final double? price;
final String? publishDate;
final bool? inStock;
Product({
required this.id,
this.author,
this.title,
this.price,
this.publishDate,
this.inStock,
});
factory Product.fromXmlElement(XmlElement element) {
return Product(
id: element.getAttribute('id') ?? '',
author: element.findElements('author').singleOrNull?.innerText,
title: element.findElements('title').singleOrNull?.innerText,
price: double.tryParse(element.findElements('price').singleOrNull?.innerText ?? ''),
publishDate: element.findElements('publish_date').singleOrNull?.innerText,
inStock: element.findElements('in_stock').singleOrNull?.innerText == 'true',
);
}
}
Why Use Strongly Typed Dart Models for XML?
Parsing XML directly in business logic using raw tag lookups like element.findElements('title') leads to fragile code. A single typo or schema change can cause unhandled exceptions during runtime.
- Compile-Time Safety: Dart’s sound type system verifies properties at compile time, eliminating typos and missing field bugs.
- Full Null Safety: Modern Dart requires explicit handling of nullable types. Models generated with null-safe parameters prevent
NullCheckcrashes when optional XML tags are omitted. - Separation of Concerns: Deserialization logic is isolated inside
fromXmlElementfactory constructors, keeping Flutter UI widgets and state management classes clean. - Fast Autocompletion: IDEs like VS Code and Android Studio provide immediate code completion for all object properties once defined in a class.
Handling Complex XML Structures in Dart
XML documents feature specific structural traits that require distinct parsing patterns in Dart:
1. Distinguishing Attributes from Elements
In XML, data can exist as an element attribute (<item id="123">) or as a nested child node (<id>123</id>). The generator differentiates between the two:
- Attributes are parsed using
.getAttribute('name'). - Child elements are resolved using
.findElements('name').
2. Repeated Child Nodes (Lists and Collections)
When an element contains multiple children with the same tag name, the converter detects the repetition and outputs a List<T> property. The factory constructor maps each child node into a nested Dart class instance.
3. Primitive Type Inference
XML values are natively stored as plain text. The converter analyzes node values and infers appropriate Dart types:
- Integers (
int) and floating-point numbers (double) viaint.tryParse()/double.tryParse(). - Booleans (
bool) by evaluating boolean literals (true/false). - Strings (
String) for standard text nodes and complex string formats.
If your incoming payloads are cluttered or unformatted, running them through an XML Pretty Print tool before conversion improves schema readability. If your backend architecture is transitioning toward RESTful JSON architectures, you can also transform schemas using an XML to JSON Converter.
Frequently Asked Questions
Does the generated code support Dart 3 sound null safety?
Yes. All generated properties, constructors, and factory parsers use null safety syntax, including required positional parameters, nullable types (?), and fallback parsing guards.
Which Dart XML package should I install to use this code?
The generated factory constructors use the standard and popular xml package from pub.dev (package:xml/xml.dart). Add xml: ^6.3.0 (or the latest version) to your pubspec.yaml file.
How does the tool distinguish between a single object and a list?
If the root or any parent node contains multiple sibling elements with identical tag names, the converter identifies them as a collection and generates a List<ChildClass> property.
How are XML namespaces handled?
Namespaces (such as <ns:element>) are sanitized into standard Dart identifier names using camelCase conventions, stripping unsupported characters to ensure the resulting code compiles cleanly.
Can I convert SOAP response envelopes into Dart classes?
Yes. Paste the complete SOAP XML envelope or just the payload inside the <soap:Body> tag. The tool extracts all nested entities and generates matching Dart classes.
What happens if an XML element has both attributes and nested text?
The generator assigns a dedicated class to that tag. Attributes become standard fields, and the inner text is mapped to a field named value or content.
Why are numeric types parsed with tryParse instead of direct casting?
Direct parsing (int.parse()) throws a FormatException if an XML field is empty, contains whitespace, or has invalid characters. Using tryParse prevents unexpected crashes and safely returns null for missing or malformed values.
Is my XML data stored or sent to a third-party server?
No. The conversion logic runs entirely on the client side inside your web browser. Your data is not stored, logged, or transmitted across external networks.
How can I handle custom DateTime formats in the output?
By default, dates are captured as String? to prevent timezone and format mismatches. You can parse them into Dart DateTime instances inside your application using DateTime.tryParse() or the intl package’s DateFormat.
Can this tool generate toJson methods for the generated Dart models?
The standard output provides fromXmlElement factory methods. If you need two-way JSON serialization, you can add toJson() maps to the generated class fields or apply annotations from packages like json_serializable.