How to create XML node root in Scala without literal name?

I want to create a document like this:

<root/> 

What can I add children to the software. Theoretically, it would look like this:

 val root_node_name = "root" val doc = <{root_node_name}/> 

But this does not work:

 error: not found: value < 

So, I tried instead:

 val root_node_name = "root" val doc = new scala.xml.Elem(null, root_node_name, null, scala.xml.TopScope, null) 

This compiles, but at runtime I get this exception from the null pointer:

 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... 

I am using Scala 2.8. Any examples of how to do this? Thanks.

+7
xml scala
source share
2 answers

You must pass an empty list of attributes ( scala.xml.Null ), and if you do not want any children, you should not even include the final argument. You need an empty list of children, not just one child that turns out 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> 
+7
source share

In 2.8 you can do this:

 scala> val r = <root/> r: scala.xml.Elem = <root></root> scala> r.copy(label="bar") res0: scala.xml.Elem = <bar></bar> 

So, if your initial document is <root/> , just use a literal. If you need to set a label at runtime, you can define a method similar to this:

 def newRoot(label:String) = {val r = <root/>; r.copy(label=label) } 
+5
source share

All Articles