创建 XML 时如何删除空格
How to remove whitespaces when we create XML
给定以下代码:
def createXmlOutput(...) : Elem =
{
<something>
{ if (condition == true) <child>{ "my child value if condition would be true" }</child> }
<otherchild>{ "my other child value" }</otherchild>
</something>
}
如果条件为假,我将得到以下输出:
<something>
<otherchild>my other child value</otherchild>
</something>
因此,如果条件为假且未放置元素,{ if.. }
块会导致额外的空行。
我怎样才能避免这种情况?我正在构建一个相当大的 XML,其中包含许多可选元素,这样做会导致多余的空格和空行。
有没有一种方法可以在创建 XML 后完全折叠空格和换行符,以便我将所有内容都放在一行中? (无论如何,这将是我的首选风格,因为它用于机器对机器的通信)
看来您必须手动添加 children 是一种方法,另一种方法是使用 scala.xml.Utility.trim
。
我已经把你的代码和 re-written 像这样:
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
}
希望对您有所帮助
如果您不手动添加 child,您也可以使用这样的东西 scala.xml.Utility.trim(createXmlOutput(true))
。
给定以下代码:
def createXmlOutput(...) : Elem =
{
<something>
{ if (condition == true) <child>{ "my child value if condition would be true" }</child> }
<otherchild>{ "my other child value" }</otherchild>
</something>
}
如果条件为假,我将得到以下输出:
<something>
<otherchild>my other child value</otherchild>
</something>
因此,如果条件为假且未放置元素,{ if.. }
块会导致额外的空行。
我怎样才能避免这种情况?我正在构建一个相当大的 XML,其中包含许多可选元素,这样做会导致多余的空格和空行。
有没有一种方法可以在创建 XML 后完全折叠空格和换行符,以便我将所有内容都放在一行中? (无论如何,这将是我的首选风格,因为它用于机器对机器的通信)
看来您必须手动添加 children 是一种方法,另一种方法是使用 scala.xml.Utility.trim
。
我已经把你的代码和 re-written 像这样:
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
}
希望对您有所帮助
如果您不手动添加 child,您也可以使用这样的东西 scala.xml.Utility.trim(createXmlOutput(true))
。