xml_serializer 0.1.0
xml_serializer: ^0.1.0 copied to clipboard
A build_runner code generator that emits XML (de)serialization logic for Dart classes annotated with xml_annotator. The build-time companion package.
xml_serializer #
A build_runner code generator for XML (de)serialization - the XML counterpart
of json_serializable.
Annotate a class, run the build, and get a .g.dart part file with
$TFromXml / $TToXml functions. No reflection, no hand-written parsing.
Install #
This is the codegen side, so it goes in dev_dependencies:
dart pub add xml_annotator
dart pub add dev:xml_serializer dev:build_runner
Requires Dart SDK ^3.10.0.
Quick start #
Annotate a class and declare the generated part:
import 'package:xml_annotator/runtime.dart';
import 'package:xml_annotator/xml_annotator.dart';
part 'reading.g.dart';
@XmlSerializer()
@XmlRoot('reading')
class Reading {
@XmlAttribute()
final String station;
@XmlElement()
final double temperature;
Reading({required this.station, required this.temperature});
// The seams that bridge to the generated functions.
factory Reading.fromXml(XmlElementNode e) => $ReadingFromXml(e);
void toXml(XmlBuilder b) => $ReadingToXml(this, b);
}
Generate the code:
dart run build_runner build
# while iterating:
dart run build_runner watch --delete-conflicting-outputs
Round-trip a value:
final xml = writeXmlDocument(
Reading(station: 'KSEA', temperature: 18.4).toXml,
declaration: false,
);
// <reading station="KSEA"><temperature>18.4</temperature></reading>
final back = Reading.fromXml(parseXmlDocument(xml));
What gets generated #
For each annotated class T, the part file defines two top-level functions:
T $TFromXml(XmlElementNode element); // read
void $TToXml(T value, XmlBuilder b); // write
Configuration #
By default the generator runs on every file under lib/. To narrow it, add a
build.yaml:
targets:
$default:
builders:
xml_serializer:
generate_for:
- lib/models/**
License #
MIT © Kawaljeet Singh