mutate<T extends TagXml> static method

T? mutate<T extends TagXml>(
  1. XmlNode? element,
  2. T constructor(), [
  3. bool force = false
])

Mutate a XmlElement into a TagXml of type T.

  • If the XmlElement is null, it returns null.
  • If the XmlElement is already an instance of T, it returns the XmlElement as T.
  • If the XmlElement is not an instance of T, it creates a new instance of T and copies the attributes and children of the XmlElement to the new instance, insert the new instance in the parent of the XmlElement and remove the XmlElement.

Implementation

static T? mutate<T extends TagXml>(XmlNode? element, T Function() constructor, [bool force = false]) {
  if (element == null) {
    if (force) return constructor();
    return null;
  }
  if (element is T && force == false) return element;

  var newTag = constructor();

  while (element.attributes.isNotEmpty) {
    var a = element.attributes.first;
    element.removeAttribute(a.name.qualified);
    newTag.setAttribute(a.name.qualified, a.value);
  }
  while (element.children.isNotEmpty) {
    var c = element.children.first;
    element.children.remove(c);
    newTag.children.add(c);
  }

  if (element.hasParent && element.parent != null) {
    var parent = element.parent!;
    var index = parent.children.indexOf(element);
    parent.children.remove(element);
    parent.children.insert(index, newTag);
  }

  return newTag;
}