Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML Creation - error: overloaded method constructor UnprefixedAttribute with alternatives

Tags:

xml

scala

scala> val count = 7
count: Int = 7

putting that into an XML attribute gives an error:

scala> val x = <element count={count}/>
<console>:8: error: overloaded method constructor UnprefixedAttribute with alternatives:
  (key: String,value: Option[Seq[scala.xml.Node]],next: scala.xml.MetaData)scala.xml.UnprefixedAttribute <and>
  (key: String,value: String,next: scala.xml.MetaData)scala.xml.UnprefixedAttribute <and>
  (key: String,value: Seq[scala.xml.Node],next1: scala.xml.MetaData)scala.xml.UnprefixedAttribute
 cannot be applied to (java.lang.String, Int, scala.xml.MetaData)
       val x = <element count={count}/>
like image 556
Trevor Avatar asked Nov 07 '11 18:11

Trevor


1 Answers

Inputs to XML attributes must be Strings. Integers and objects will not automatically be converted to Strings using their toString method. For example if you defined a Size class using a Units enum:

scala> object Units extends Enumeration {
     |   type Units = Value
     |   val COUNT = Value("count")
     |   val LB = Value("pounds")
     |   val OZ = Value("ounces")
     |   val GRAM = Value("grams")
     |   val KG = Value("kilograms")
     |   val GAL = Value("gallons")
     |   val QT = Value("quarts")
     |   val PINT = Value("pints")
     |   val FL_OZ = Value("fluid ounces")
     |   val L = Value("liters")
     | }
defined module Units


scala> class Size(val value: Double, val unit: Units.Units) {
     | override def toString = value + " " + unit.toString
     | }
defined class Size

created an instance of Size:

scala> val seven = new Size(7, Units.COUNT)
seven: Size = 7.0 count

then tried to put your size into an XML attribute, you would still get an error:

scala> val x = <element size={seven}/>
<console>:10: error: overloaded method constructor UnprefixedAttribute with alternatives:
  (key: String,value: Option[Seq[scala.xml.Node]],next: scala.xml.MetaData)scala.xml.UnprefixedAttribute <and>
  (key: String,value: String,next: scala.xml.MetaData)scala.xml.UnprefixedAttribute <and>
  (key: String,value: Seq[scala.xml.Node],next1: scala.xml.MetaData)scala.xml.UnprefixedAttribute
 cannot be applied to (java.lang.String, Size, scala.xml.MetaData)
       val x = <element size={seven}/>
                ^

You must explicitly call the toString method. This works:

scala> val x = <element count={count.toString} size={seven.toString}/>
x: scala.xml.Elem = <element size="7.0 count" count="7"></element>
like image 142
Trevor Avatar answered Nov 10 '22 05:11

Trevor