element method
Adds a XmlElement node with the provided tag name
.
If a namespace
URI is provided, the prefix is looked up, verified and
combined with the given tag name
.
If a map of namespaces
is provided the uri-prefix pairs are added to the
element declaration, see also XmlBuilder.namespace.
If a map of attributes
is provided the name-value pairs are added to the
element declaration, see also XmlBuilder.attribute.
Finally, nest
is used to further customize the element and to add its
children. Typically this is a Function that defines elements using the
same builder object. For convenience nest
can also be a valid XmlNode,
a string or another common object that will be converted to a string and
added as a text node.
For example, to generate an XML element with the tag message and the contained text Hello World one would write:
builder.element('message', nest: 'Hello World');
To add multiple child elements one would use:
builder.element('message', nest: () {
builder..text('Hello World')
..element('break');
});
Implementation
void element(String name,
{String? namespace,
Map<String, String?> namespaces = const {},
Map<String, String> attributes = const {},
bool isSelfClosing = true,
Object? nest}) {
final element = NodeBuilder();
_stack.addLast(element);
namespaces.forEach(this.namespace);
attributes.forEach(attribute);
if (nest != null) {
_insert(nest);
}
element.name = _buildName(name, namespace);
element.isSelfClosing = isSelfClosing;
if (optimizeNamespaces) {
// Remove unused namespaces: The reason we first add them and then remove
// them again is to keep the order in which they have been added.
element.namespaces.forEach((uri, meta) {
if (!meta.used) {
final name = meta.name;
final attribute = element.attributes.firstWhere((attribute) => attribute.name == name);
element.attributes.remove(attribute);
}
});
}
_stack.removeLast();
_stack.last.children.add(element.buildElement());
}