如何在 Scala XML 输出中生成整数文字作为属性?
我希望以下代码生成包含以下内容的 XML 值:
<TestInteger value="10"/>
编译器给出错误
scala> import scala.xml._
import scala.xml._
scala> val x:Int = 10
x: Int = 10
scala> <TestInteger value={x}/>
<console>:8: error: overloaded method constructor UnprefixedAttribute with alternatives (String,Option[Seq[scala.xml.Node]],scala.xml.MetaData)scala.xml.UnprefixedAttribute <and> (String,String,scala.xml.MetaData)scala.xml.UnprefixedAttribute <and> (String,Seq[scala.xml.Node],scala.xml.MetaData)scala.xml.UnprefixedAttribute cannot be applied to (java.lang.String,Int,scala.xml.MetaData)
<TestInteger value={x}/>
我做错了什么? XML 中允许使用整数吗?
我正在使用 Scala 2.7.7
I expect the following code to produce XML value with the following content:
<TestInteger value="10"/>
Compiler gives of an error
scala> import scala.xml._
import scala.xml._
scala> val x:Int = 10
x: Int = 10
scala> <TestInteger value={x}/>
<console>:8: error: overloaded method constructor UnprefixedAttribute with alternatives (String,Option[Seq[scala.xml.Node]],scala.xml.MetaData)scala.xml.UnprefixedAttribute <and> (String,String,scala.xml.MetaData)scala.xml.UnprefixedAttribute <and> (String,Seq[scala.xml.Node],scala.xml.MetaData)scala.xml.UnprefixedAttribute cannot be applied to (java.lang.String,Int,scala.xml.MetaData)
<TestInteger value={x}/>
What am I doing wrong? Are integer literals allowed in XML?
I'm using Scala 2.7.7
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据 this 每个属性值,您的 XML 似乎违反了 XML 规范必须以双引号开头。请参阅 AttValue 规则。
编辑:
经过一番谷歌搜索后,似乎 scala.xml.UnprefixedAttribute 具有仅支持字符串作为值的构造函数,因此由于没有从 Int 到 String 的内置隐式转换,因此您的这段代码将与代码不同:
Scala 现在不知道如何自动将整数转换为字符串,但以下代码将工作
Look like your XML is violating XML specification according to this each attribute value must begin with a double quote. See AttValue rule.
Edit:
After some googling around it seems that scala.xml.UnprefixedAttribute has Constructor that only supports strings as values so since there is no build-in implicit conversion from Int's to String this code of yours will not work same as code :
Scala doesn't now how convert integers to strings automatically but following code however will work
Scala XML 不支持
String
以外的任何类型。 可以扩展该库以添加Text
的替代方案,但是,事实上,没有支持。Scala XML has no support for any type other than
String
. One can extend the library to add alternatives toText
, but, as it is, there's no support.