Reputation: 3206
Given the following code:
def createXmlOutput(...) : Elem =
{
<something>
{ if (condition == true) <child>{ "my child value if condition would be true" }</child> }
<otherchild>{ "my other child value" }</otherchild>
</something>
}
I will get the following output in case the condition is false:
<something>
<otherchild>my other child value</otherchild>
</something>
So, the { if.. }
block leads to an extra blank line in case the condition is false and the element is not placed.
How can I avoid this? I am building a rather large XML with lots of optional elements, which leads to excess whitespace and empty lines when doing it this way.
Is there a way to completely collapse whitespace & newlines after creating the XML, so I have it all in one line? (which would be my preferred style anyway, because its for machine-to-machine communication)
Upvotes: 1
Views: 610
Reputation: 725
Looks like you have to add children manually is one way and another way is to use scala.xml.Utility.trim
.
I have taken your code and re-written like this :
def createXmlOutput(condition:Boolean) : Elem =
{
val parent: Elem = <something>
<otherchild>{ "my other child value" }</otherchild>
</something>
val child = <child>{ "my child value if condition would be true" }</child>
if(condition == true) parent.copy(child = parent.child :+ child)
else parent
}
Hope this helps
And also you can use something like this scala.xml.Utility.trim(createXmlOutput(true))
if you are not adding the child manually.
Upvotes: 4