attribute method

void attribute(
  1. String name,
  2. Object? value, {
  3. String? namespace,
  4. XmlAttributeType? attributeType,
})

Adds a XmlAttribute node with the provided name and value.

If a namespace URI is provided, the prefix is looked up, verified and combined with the given attribute name.

To generate an element with the tag message and the attribute lang="en" one would write:

builder.element('message', nest: () {
   builder.attribute('lang', 'en');
});

Implementation

void attribute(String name, Object? value,
    {String? namespace, XmlAttributeType? attributeType}) {
  final attributes = _stack.last.attributes;
  final attributeName = _buildName(name, namespace);
  final attributeIndex = attributes.indexWhere((attribute) =>
      attribute.localName == attributeName.local &&
      attribute.namespacePrefix == attributeName.prefix);
  if (attributeIndex < 0) {
    if (value != null) {
      final attribute = XmlAttribute(_buildName(name, namespace),
          value.toString(), attributeType ?? XmlAttributeType.DOUBLE_QUOTE);
      attributes.add(attribute);
    }
  } else {
    if (value != null) {
      attributes[attributeIndex].value = value.toString();
    } else {
      attributes.removeAt(attributeIndex);
    }
  }
}