代码之家  ›  专栏  ›  技术社区  ›  user826955

创建XML时如何删除空白

  •  1
  • user826955  · 技术社区  · 7 年前

    给定以下代码:

    def createXmlOutput(...) : Elem =
    {
       <something>
         { if (condition == true) <child>{ "my child value if condition would be true" }</child> }
         <otherchild>{ "my other child value" }</otherchild>
       </something>
    }
    

    如果条件为false,我将获得以下输出:

    <something>
    
      <otherchild>my other child value</otherchild>
    </something>
    

    { if.. } 如果条件为false且未放置元素,则块将导致额外的空行。

    有没有一种方法可以完全压缩空白&创建XML后的换行符,所以我将所有内容都放在一行中(哪一种是我最喜欢的风格,因为它用于机器对机器的通信)

    1 回复  |  直到 7 年前
        1
  •  4
  •   Amit Prasad    7 年前

    scala.xml.Utility.trim .

     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
     }
    

    你也可以用这样的东西 scala.xml.Utility.trim(createXmlOutput(true))

    推荐文章