eu.cdevreeze.yaidom.queryapi

UpdatableElemApi

trait UpdatableElemApi[N, E <: N with UpdatableElemApi[N, E]] extends IsNavigableApi[E]

This is the functional update part of the yaidom uniform query API. It is a sub-trait of trait eu.cdevreeze.yaidom.queryapi.IsNavigableApi. Only a few DOM-like element implementations in yaidom mix in this trait (indirectly, because some implementing sub-trait is mixed in), thus sharing this query API.

This trait typically does not show up in application code using yaidom, yet its (uniform) API does. Hence, it makes sense to read the documentation of this trait, knowing that the API is offered by multiple element implementations.

This trait is purely abstract. The most common implementation of this trait is eu.cdevreeze.yaidom.queryapi.UpdatableElemLike. The trait has all the knowledge of its super-trait, but in addition to that knows the following:

Obviously methods children, withChildren and childNodeIndex must be consistent with methods such as findAllChildElems.

Using this minimal knowledge alone, trait UpdatableElemLike not only offers the methods of its parent trait, but also:

For the conceptual difference with "transformable" elements, see trait eu.cdevreeze.yaidom.queryapi.TransformableElemApi.

This query API leverages the Scala Collections API. Query results can be manipulated using the Collections API, and the query API implementation (in UpdatableElemLike) uses the Collections API internally.

UpdatableElemApi examples

To illustrate the use of this API, consider the following example XML:

<book:Bookstore xmlns:book="http://bookstore/book" xmlns:auth="http://bookstore/author">
  <book:Book ISBN="978-0321356680" Price="35" Edition="2">
    <book:Title>Effective Java (2nd Edition)</book:Title>
    <book:Authors>
      <auth:Author>
        <auth:First_Name>Joshua</auth:First_Name>
        <auth:Last_Name>Bloch</auth:Last_Name>
      </auth:Author>
    </book:Authors>
  </book:Book>
  <book:Book ISBN="978-0981531649" Price="35" Edition="2">
    <book:Title>Programming in Scala: A Comprehensive Step-by-Step Guide, 2nd Edition</book:Title>
    <book:Authors>
      <auth:Author>
        <auth:First_Name>Martin</auth:First_Name>
        <auth:Last_Name>Odersky</auth:Last_Name>
      </auth:Author>
      <auth:Author>
        <auth:First_Name>Lex</auth:First_Name>
        <auth:Last_Name>Spoon</auth:Last_Name>
      </auth:Author>
      <auth:Author>
        <auth:First_Name>Bill</auth:First_Name>
        <auth:Last_Name>Venners</auth:Last_Name>
      </auth:Author>
    </book:Authors>
  </book:Book>
</book:Bookstore>

Suppose this XML has been parsed into eu.cdevreeze.yaidom.simple.Elem variable named bookstoreElem. Then we can add a book as follows, where we "forget" the 2nd author for the moment:

import convert.ScalaXmlConversions._

val bookstoreNamespace = "http://bookstore/book"
val authorNamespace = "http://bookstore/author"

val fpBookXml =
  <book:Book xmlns:book="http://bookstore/book" xmlns:auth="http://bookstore/author" ISBN="978-1617290657" Price="33">
    <book:Title>Functional Programming in Scala</book:Title>
    <book:Authors>
      <auth:Author>
        <auth:First_Name>Paul</auth:First_Name>
        <auth:Last_Name>Chiusano</auth:Last_Name>
      </auth:Author>
    </book:Authors>
  </book:Book>
val fpBookElem = convertToElem(fpBookXml)

bookstoreElem = bookstoreElem.plusChild(fpBookElem)

Note that the namespace declarations for prefixes book and auth had to be repeated in the Scala XML literal for the added book, because otherwise the convertToElem method would throw an exception (since Elem instances cannot be created unless all element and attribute QNames can be resolved as ENames).

The resulting bookstore seems ok, but if we print convertElem(bookstoreElem), the result does not look pretty. This can be fixed if the last assignment is replaced by:

bookstoreElem = bookstoreElem.plusChild(fpBookElem).prettify(2)

knowing that an indentation of 2 spaces has been used throughout the original XML. Method prettify is expensive, so it is best not to invoke it within a tight loop. As an alternative, formatting can be left to the DocumentPrinter, of course.

The assignment above is the same as the following one:

bookstoreElem = bookstoreElem.withChildren(bookstoreElem.children :+ fpBookElem).prettify(2)

There are several methods to functionally update the children of an element. For example, method plusChild is overloaded, and the other variant can insert a child at a given 0-based position. Other "children update" methods are minusChild, withPatchedChildren and withUpdatedChildren.

Let's now turn to functional update methods that take Path instances or collections thereof. In the example above the second author of the added book is missing. Let's fix that:

val secondAuthorXml =
  <auth:Author xmlns:auth="http://bookstore/author">
    <auth:First_Name>Runar</auth:First_Name>
    <auth:Last_Name>Bjarnason</auth:Last_Name>
  </auth:Author>
val secondAuthorElem = convertToElem(secondAuthorXml)

val fpBookAuthorsPaths =
  for {
    authorsPath <- indexed.Elem(bookstoreElem) filterElems { e => e.resolvedName == EName(bookstoreNamespace, "Authors") } map (_.path)
    if authorsPath.findAncestorPath(path => path.endsWithName(EName(bookstoreNamespace, "Book")) &&
      bookstoreElem.getElemOrSelfByPath(path).attribute(EName("ISBN")) == "978-1617290657").isDefined
  } yield authorsPath

require(fpBookAuthorsPaths.size == 1)
val fpBookAuthorsPath = fpBookAuthorsPaths.head

bookstoreElem = bookstoreElem.updated(fpBookAuthorsPath) { elem =>
  require(elem.resolvedName == EName(bookstoreNamespace, "Authors"))
  val rawResult = elem.plusChild(secondAuthorElem)
  rawResult transformElemsOrSelf (e => e.copy(scope = elem.scope.withoutDefaultNamespace ++ e.scope))
}
bookstoreElem = bookstoreElem.prettify(2)

Clearly the resulting bookstore element is nicely formatted, but there was another possible issue that was taken into account. See the line of code transforming the "raw result". That line was added in order to prevent namespace undeclarations, which for XML version 1.0 are not allowed (with the exception of the default namespace). After all, the XML for the second author was created with only the auth namespace declared. Without the above-mentioned line of code, a namespace undeclaration for prefix book would have occurred in the resulting XML, thus leading to an invalid XML 1.0 element tree.

To illustrate functional update methods taking collections of paths, let's remove the added book from the book store. Here is one (somewhat inefficient) way to do that:

val bookPaths = indexed.Elem(bookstoreElem) filterElems (_.resolvedName == EName(bookstoreNamespace, "Book")) map (_.path)

bookstoreElem = bookstoreElem.updatedWithNodeSeqAtPaths(bookPaths.toSet) { (elem, path) =>
  if ((elem \@ EName("ISBN")) == Some("978-1617290657")) Vector() else Vector(elem)
}
bookstoreElem = bookstoreElem.prettify(2)

There are very many ways to write this functional update, using different functional update methods in trait UpdatableElemApi, or even only using transformation methods in trait TransformableElemApi (thus not using paths).

The example code above is enough to get started using the UpdatableElemApi methods, but it makes sense to study the entire API, and practice with it. Always keep in mind that functional updates typically mess up formatting and/or namespace (un)declarations, unless these aspects are taken into account.

N

The node supertype of the element subtype

E

The captured element subtype

Self Type
E
Linear Supertypes
IsNavigableApi[E], AnyRef, Any
Known Subclasses
Ordering
  1. Alphabetic
  2. By inheritance
Inherited
  1. UpdatableElemApi
  2. IsNavigableApi
  3. AnyRef
  4. Any
  1. Hide All
  2. Show all
Learn more about member selection
Visibility
  1. Public
  2. All

Abstract Value Members

  1. abstract def childNodeIndex(childPathEntry: Entry): Int

    Returns the child node index of the child element at the given path entry, if any, and -1 otherwise.

    Returns the child node index of the child element at the given path entry, if any, and -1 otherwise. The faster this method is, the better.

  2. abstract def children: IndexedSeq[N]

    Returns the child nodes of this element, in the correct order

  3. abstract def findChildElemByPathEntry(entry: Entry): Option[E]

    Finds the child element with the given Path.Entry (where this element is the root), if any, wrapped in an Option.

    Finds the child element with the given Path.Entry (where this element is the root), if any, wrapped in an Option.

    Typically this method must be very efficient, in order for methods like findElemOrSelfByPath to be efficient.

    Definition Classes
    IsNavigableApi
  4. abstract def findElemOrSelfByPath(path: Path): Option[E]

    Finds the element with the given Path (where this element is the root), if any, wrapped in an Option.

    Finds the element with the given Path (where this element is the root), if any, wrapped in an Option.

    That is, returns:

    findReverseAncestryOrSelfByPath(path).map(_.last)

    Note that for each non-empty Path, we have:

    findElemOrSelfByPath(path) == findChildElemByPathEntry(path.firstEntry) flatMap (e => e.findElemOrSelfByPath(path.withoutFirstEntry))
    Definition Classes
    IsNavigableApi
  5. abstract def findReverseAncestryOrSelfByPath(path: Path): Option[IndexedSeq[E]]

    Finds the reversed ancestry-or-self of the element with the given Path (where this element is the root), wrapped in an Option.

    Finds the reversed ancestry-or-self of the element with the given Path (where this element is the root), wrapped in an Option. None is returned if no element can be found at the given Path.

    Hence, the resulting element collection, if any, starts with this element and ends with the element at the given Path, relative to this element.

    This method comes in handy for (efficiently) computing base URIs, where the (reverse) ancestry-or-self is needed as input.

    Definition Classes
    IsNavigableApi
  6. abstract def getChildElemByPathEntry(entry: Entry): E

    Returns (the equivalent of) findChildElemByPathEntry(entry).get

    Returns (the equivalent of) findChildElemByPathEntry(entry).get

    Definition Classes
    IsNavigableApi
  7. abstract def getElemOrSelfByPath(path: Path): E

    Returns (the equivalent of) findElemOrSelfByPath(path).get

    Returns (the equivalent of) findElemOrSelfByPath(path).get

    Definition Classes
    IsNavigableApi
  8. abstract def getReverseAncestryOrSelfByPath(path: Path): IndexedSeq[E]

    Returns (the equivalent of) findReverseAncestryOrSelfByPath(path).get

    Returns (the equivalent of) findReverseAncestryOrSelfByPath(path).get

    Definition Classes
    IsNavigableApi
  9. abstract def minusChild(index: Int): E

    Returns a copy in which the child at the given position (0-based) has been removed.

    Returns a copy in which the child at the given position (0-based) has been removed. Throws an exception if index >= children.size.

  10. abstract def plusChild(child: N): E

    Returns a copy in which the given child has been inserted at the end

  11. abstract def plusChild(index: Int, child: N): E

    Returns a copy in which the given child has been inserted at the given position (0-based).

    Returns a copy in which the given child has been inserted at the given position (0-based). If index == children.size, adds the element at the end. If index > children.size, throws an exception.

    Afterwards, the resulting element indeed has the given child at position index (0-based).

  12. abstract def plusChildOption(childOption: Option[N]): E

    Returns a copy in which the given child, if any, has been inserted at the end.

    Returns a copy in which the given child, if any, has been inserted at the end. That is, returns plusChild(childOption.get) if the given optional child element is non-empty.

  13. abstract def plusChildOption(index: Int, childOption: Option[N]): E

    Returns a copy in which the given child, if any, has been inserted at the given position (0-based).

    Returns a copy in which the given child, if any, has been inserted at the given position (0-based). That is, returns plusChild(index, childOption.get) if the given optional child element is non-empty.

  14. abstract def plusChildren(childSeq: IndexedSeq[N]): E

    Returns a copy in which the given children have been inserted at the end

  15. abstract def updated(path: Path, newElem: E): E

    Returns updated(path) { e => newElem }

  16. abstract def updated(path: Path)(f: (E) ⇒ E): E

    Method that "functionally updates" the tree with this element as root element, by applying the passed function to the element that has the given eu.cdevreeze.yaidom.core.Path (compared to this element as root).

    Method that "functionally updates" the tree with this element as root element, by applying the passed function to the element that has the given eu.cdevreeze.yaidom.core.Path (compared to this element as root).

    The method throws an exception if no element is found with the given path.

    It can be defined (recursively) as follows:

    if (path == Path.Root) f(self)
    else updated(path.firstEntry) { e => e.updated(path.withoutFirstEntry)(f) }
  17. abstract def updated(pathEntry: Entry)(f: (E) ⇒ E): E

    Core method that "functionally updates" the tree with this element as root element, by applying the passed function to the element that has the given eu.cdevreeze.yaidom.core.Path.Entry (compared to this element as root).

    Core method that "functionally updates" the tree with this element as root element, by applying the passed function to the element that has the given eu.cdevreeze.yaidom.core.Path.Entry (compared to this element as root).

    The method throws an exception if no element is found with the given path entry.

    It can be defined as follows:

    val idx = self.childNodeIndex(pathEntry)
    self.withUpdatedChildren(idx, f(children(idx).asInstanceOf[E]))
  18. abstract def updatedAtPathEntries(pathEntries: Set[Entry])(f: (E, Entry) ⇒ E): E

    Method that "functionally updates" the tree with this element as root element, by applying the passed function to all child elements with the given path entries (compared to this element as root).

    Method that "functionally updates" the tree with this element as root element, by applying the passed function to all child elements with the given path entries (compared to this element as root).

    It can be defined as follows (ignoring exceptions):

    val newChildren = pathEntries.toSeq.map(entry => (entry -> childNodeIndex(entry))).sortBy(_._2).reverse.foldLeft(children) {
      case (acc, (pathEntry, idx)) =>
        acc.updated(idx, f(acc(idx).asInstanceOf[E], pathEntry))
    }
    withChildren(newChildren)
  19. abstract def updatedAtPaths(paths: Set[Path])(f: (E, Path) ⇒ E): E

    Method that "functionally updates" the tree with this element as root element, by applying the passed function to all descendant-or-self elements with the given paths (compared to this element as root).

    Method that "functionally updates" the tree with this element as root element, by applying the passed function to all descendant-or-self elements with the given paths (compared to this element as root).

    It can be defined (recursively) as follows (ignoring exceptions):

    def updatedAtPaths(paths: Set[Path])(f: (E, Path) => E): E = {
    val pathsByPathEntries = paths.filter(path => !path.isRoot).groupBy(path => path.firstEntry)
    val resultWithoutSelf = self.updatedAtPathEntries(pathsByPathEntries.keySet) { (che, pathEntry) =>
      val newChe = che.updatedAtPaths(paths.map(_.withoutFirstEntry)) { (elem, relativePath) =>
        f(elem, relativePath.prepend(pathEntry))
      }
      newChe
    }
    if (paths.contains(Path.Root)) f(resultWithoutSelf, Path.Root) else resultWithoutSelf
    }

    For simple elements, it is also equivalent to:

    val pathsReversed = indexed.Elem(this).findAllElemsOrSelf.map(_.path).filter(p => paths.contains(p)).reverse
    pathsReversed.foldLeft(self) { case (acc, path) => acc.updated(path) { e => f(e, path) } }
  20. abstract def updatedWithNodeSeq(path: Path, newNodes: IndexedSeq[N]): E

    Returns updatedWithNodeSeq(path) { e => newNodes }

  21. abstract def updatedWithNodeSeq(path: Path)(f: (E) ⇒ IndexedSeq[N]): E

    "Functionally updates" the tree with this element as root element, by applying the passed function to the element that has the given eu.cdevreeze.yaidom.core.Path (compared to this element as root).

    "Functionally updates" the tree with this element as root element, by applying the passed function to the element that has the given eu.cdevreeze.yaidom.core.Path (compared to this element as root). If the given path is the root path, this element itself is returned unchanged.

    This function could be defined as follows:

    // First define function g as follows:
    
    def g(e: Elem): Elem = {
      if (path == Path.Root) e
      else {
        e.withPatchedChildren(
          e.childNodeIndex(path.lastEntry),
          f(e.findChildElemByPathEntry(path.lastEntry).get),
          1)
      }
    }
    
    // Then the function updatedWithNodeSeq(path)(f) could be defined as:
    
    updated(path.parentPathOption.getOrElse(Path.Root))(g)

    After all, this is just a functional update that replaces the parent element, if it exists.

    The method throws an exception if no element is found with the given path.

  22. abstract def updatedWithNodeSeqAtPathEntries(pathEntries: Set[Entry])(f: (E, Entry) ⇒ IndexedSeq[N]): E

    Method that "functionally updates" the tree with this element as root element, by applying the passed function to all child elements with the given path entries (compared to this element as root).

    Method that "functionally updates" the tree with this element as root element, by applying the passed function to all child elements with the given path entries (compared to this element as root).

    It can be defined as follows (ignoring exceptions):

    val indexesByPathEntries = pathEntries.toSeq.map(entry => (entry -> childNodeIndex(entry))).sortBy(_._2).reverse
    val newChildGroups =
      indexesByPathEntries.foldLeft(self.children.map(n => immutable.IndexedSeq(n))) {
        case (acc, (pathEntry, idx)) =>
          acc.updated(idx, f(acc(idx).head.asInstanceOf[E], pathEntry))
      }
    withChildren(newChildGroups.flatten)
  23. abstract def updatedWithNodeSeqAtPaths(paths: Set[Path])(f: (E, Path) ⇒ IndexedSeq[N]): E

    Method that "functionally updates" the tree with this element as root element, by applying the passed function to all descendant elements with the given paths (compared to this element as root), but ignoring the root path.

    Method that "functionally updates" the tree with this element as root element, by applying the passed function to all descendant elements with the given paths (compared to this element as root), but ignoring the root path.

    It can be defined as follows (ignoring exceptions):

    val pathsByParentPaths = paths.filter(path => !path.isRoot).groupBy(path => path.parentPath)
    self.updatedAtPaths(pathsByParentPaths.keySet) { (elem, path) =>
      val childPathEntries = pathsByParentPaths(path).map(_.lastEntry)
      elem.updatedWithNodeSeqAtPathEntries(childPathEntries) { (che, pathEntry) =>
        f(che, path.append(pathEntry))
      }
    }
  24. abstract def withChildSeqs(newChildSeqs: IndexedSeq[IndexedSeq[N]]): E

    Shorthand for withChildren(newChildSeqs.flatten)

  25. abstract def withChildren(newChildren: IndexedSeq[N]): E

    Returns an element with the same name, attributes and scope as this element, but with the given child nodes

  26. abstract def withPatchedChildren(from: Int, newChildren: IndexedSeq[N], replace: Int): E

    Shorthand for withChildren(children.patch(from, newChildren, replace))

  27. abstract def withUpdatedChildren(index: Int, newChild: N): E

    Shorthand for withChildren(children.updated(index, newChild))

Concrete Value Members

  1. final def !=(arg0: AnyRef): Boolean

    Definition Classes
    AnyRef
  2. final def !=(arg0: Any): Boolean

    Definition Classes
    Any
  3. final def ##(): Int

    Definition Classes
    AnyRef → Any
  4. final def ==(arg0: AnyRef): Boolean

    Definition Classes
    AnyRef
  5. final def ==(arg0: Any): Boolean

    Definition Classes
    Any
  6. final def asInstanceOf[T0]: T0

    Definition Classes
    Any
  7. def clone(): AnyRef

    Attributes
    protected[java.lang]
    Definition Classes
    AnyRef
    Annotations
    @throws( ... )
  8. final def eq(arg0: AnyRef): Boolean

    Definition Classes
    AnyRef
  9. def equals(arg0: Any): Boolean

    Definition Classes
    AnyRef → Any
  10. def finalize(): Unit

    Attributes
    protected[java.lang]
    Definition Classes
    AnyRef
    Annotations
    @throws( classOf[java.lang.Throwable] )
  11. final def getClass(): Class[_]

    Definition Classes
    AnyRef → Any
  12. def hashCode(): Int

    Definition Classes
    AnyRef → Any
  13. final def isInstanceOf[T0]: Boolean

    Definition Classes
    Any
  14. final def ne(arg0: AnyRef): Boolean

    Definition Classes
    AnyRef
  15. final def notify(): Unit

    Definition Classes
    AnyRef
  16. final def notifyAll(): Unit

    Definition Classes
    AnyRef
  17. final def synchronized[T0](arg0: ⇒ T0): T0

    Definition Classes
    AnyRef
  18. def toString(): String

    Definition Classes
    AnyRef → Any
  19. final def wait(): Unit

    Definition Classes
    AnyRef
    Annotations
    @throws( ... )
  20. final def wait(arg0: Long, arg1: Int): Unit

    Definition Classes
    AnyRef
    Annotations
    @throws( ... )
  21. final def wait(arg0: Long): Unit

    Definition Classes
    AnyRef
    Annotations
    @throws( ... )

Inherited from IsNavigableApi[E]

Inherited from AnyRef

Inherited from Any

Ungrouped