문제

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??

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top