XML Creation - 错误:重载方法构造函数UnprefixedAttribute with alternatives

时间:2011-11-07 18:50:32

标签: xml scala

scala> val count = 7
count: Int = 7

将它放入XML属性会产生错误:

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

1 个答案:

答案 0 :(得分:24)

XML属性的输入必须是字符串。整数和对象不会使用其toString方法自动转换为字符串。 例如,如果使用Units enum:

定义了Size类
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

创建了一个Size:

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

然后尝试将您的大小放入XML属性中,您仍然会收到错误:

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

您必须显式调用toString方法。这有效:

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