如何在没有文字元素名称的情况下在 Scala 中创建 XML 根节点? [英] How do I create an XML root node in Scala without a literal element name?
问题描述
我想创建一个这样的文档:
I'm looking to create a document like this:
<root/>
我可以以编程方式添加子项.理论上,它看起来像这样:
That I can add children to programatically. Theoretically, it would look like this:
val root_node_name = "root"
val doc = <{root_node_name}/>
但这似乎不起作用:
error: not found: value <
所以,我尝试的是这样的:
So, what I tried instead was this:
val root_node_name = "root"
val doc = new scala.xml.Elem(null, root_node_name, null, scala.xml.TopScope, null)
那可以编译,但在运行时我得到这个空指针异常:
That compiles but at runtime I get this null pointer exception:
java.lang.NullPointerException
at scala.xml.Utility$.toXML(Utility.scala:201)
at scala.xml.Utility$$anonfun$sequenceToXML$2.apply(Utility.scala:235)
at scala.xml.Utility$$anonfun$sequenceToXML$2.apply(Utility.scala:235)
at scala.Iterator$class.foreach(Iterator.scala:414)
at scala.runtime.BoxedArray$AnyIterator.foreach(BoxedArray.scala:45)
at scala.Iterable$class.foreach(Iterable...
我使用的是 Scala 2.8.任何有关如何实现这一目标的示例?谢谢.
I'm using Scala 2.8. Any examples of how to pull this off? Thanks.
推荐答案
你应该传递属性的空列表 (scala.xml.Null
),如果你不想要任何孩子,你甚至不应该包括最后的论点.您需要一个空的子项列表,而不是一个恰好为 null
的子项.所以:
You should pass the empty list for attributes (scala.xml.Null
) and if you don't want any children, you shouldn't even include the final argument. You want an empty list of children, not a single child that happens to be null
. So:
scala> val root_node_name = "root"
root_node_name: java.lang.String = root
scala> val doc = new scala.xml.Elem(null, root_node_name, scala.xml.Null , scala.xml.TopScope)
doc: scala.xml.Elem = <root></root>
这篇关于如何在没有文字元素名称的情况下在 Scala 中创建 XML 根节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!