Frage

Ran across this ancient thread on applying varargs to an XML node, but no definitive answer for this particular problem came of it (accepted answer answers everything but this issue).

Have a pretty gruesome hack in place to avoid resorting to XML.loadString("...") for generating XHTML form fields.

def nodeCopy(e: Elem, args: (Symbol,Any)*): Elem = {

  val a = args.map{case(s,v)=> Attribute(None,s.name,Text(v.toString),Null) }
  a.size match{
    case 0 => e
    case 1 => e % a(0)
    case 2 => e % a(0) % a(1) 
    case 3 => e % a(0) % a(1) % a(2)
    case 4 => e % a(0) % a(1) % a(2) % a(3)
    case 5 => e % a(0) % a(1) % a(2) % a(3) % a(4)
    case 6 => e % a(0) % a(1) % a(2) % a(3) % a(4) % a(5)
    case _ => e % a(0) % a(1) % a(2) % a(3) % a(4) % a(5) % a(6)
  }
}

// usage (where args could be: ('id, "foo"), ('class, "bar"), ...)
nodeCopy(<input name={k} value={v} />, args:_*)

Is there a better approach to generating dynamic XML Elems with Scala 2.10??

War es hilfreich?

Lösung

Here's a very literal translation into a fold:

def nodeCopy(e: Elem, args: (Symbol, Any)*): Elem = args.foldLeft(e) {
  case (currentElem, (s, v)) =>
    currentElem % Attribute(None, s.name, Text(v.toString), Null)
}

This works the same as your implementation, but for arbitrarily many attributes.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top