doub1ejack doub1ejack - 1 year ago 177
Scala Question

How to cast a Scala Elem to a NodeSeq

I am trying to write an XML RewriteRule that will wrap a child element inside a wrapper element in an effort to normalize a bunch of different xml files. This does what I need it to, but I end up with an Elem and in order to override the

function, I need to return a NodeSeq.

* Some Nodes should be wrapped in an enclosing Node. For example, some xml versions
* of the article <contentitem> have <category> as a direct child, but category info
* should really have this structure:
* <categories>
* <category>some category name</category>
* </categories>
val wrapIndividualNodes = new RewriteRule {
val nodesToWrap = List( ("category", "categories"), ("subcategory", "subcategories") )

override def transform(n: Node): NodeSeq = {
for ( (target, wrapper) <- nodesToWrap ) {

// copy, then delete, children
val categoryNodes = (n \ target)
val articleWithoutCategoryNodes = SharedRules.deleteChildren(n, target)

// wrap children and add as new child
val categories = <categories>{categoryNodes}</categories>
SharedRules.addChild(articleWithoutCategoryNodes, categories)



* Adds newChild as the last element in the parent node
def addChild(parent: Node, child: Node): Elem = {
parent.copy(child = parent.child ++ child)

* Deletes all children with matching childLabel from parent
def deleteChildren(parent: Node, childLabel: String): Elem = {
parent.copy( child = parent.child.filterNot(_.label == childLabel))

Answer Source

Not sure it is really what you ask bug I guess this sould work :

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download