2011-11-07 12 views
12
scala> val count = 7 
count: Int = 7 

mettere che in un attributo XML dà un errore:XML Creazione - errore: sovraccarico metodo di costruzione UnprefixedAttribute con alternative

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}/> 

risposta

23

ingressi agli attributi XML devono essere stringhe. I numeri interi e gli oggetti non verranno automaticamente convertiti in stringhe utilizzando il loro metodo toString. Per esempio, se è stata definita una classe di dimensione utilizzando un enum Unità:

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 

creato un'istanza di Dimensione:

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

poi ha cercato di mettere la vostra dimensione in un attributo XML, si sarebbe comunque ottenere un errore:

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}/> 
       ^

È necessario chiamare esplicitamente il metodo toString. Funziona:

scala> val x = <element count={count.toString} size={seven.toString}/> 
x: scala.xml.Elem = <element size="7.0 count" count="7"></element> 
Problemi correlati