ScalaXML 和空行

ScalaXML and empty lines

我刚刚开始使用 scala,在将我的域对象 (case class) 表示为格式良好的 XML 时遇到了问题。我有以下隐式转换器:

implicit def identifierToXml(ident : Identifier): Elem =
    <identifier>
        { if(ident.use != null) <use value={ident.use}/> }
        { if(ident.label != null) <label value={ident.label}/> }
        { if(ident.system != null) <system value={ident.system}/> }
        { if(ident.value != null) <value value={ident.value}/> }
        { if(ident.period != null) <period>{ident.period}</period> }
        { if(ident.assigner != null) <assigner>{ident.assigner}</assigner> }
    </identifier>

它工作得很好,除了它会在缺失值上插入空行。例如 Identifier(system = "test") 结果:

<identifier>


    <system value="test"/>



</identifier>

我知道我可以使用 scala.xml.Utility.trim(...) 转换为完全修剪的表示形式 (<identifier><system value="test"/></identifier>),但宁愿保留空行除外的格式。

我怎样才能以惯用的方式实现这一目标?如果我要使用 scala.xml.Utility.trim(...),是否有将其添加到我的隐式转换器的好方法?

注意。另外,如果有更好的方法来处理 object <-> xml 表示之间的这种转换,我很想听听建议:)

问题只是在构造 XML 文字时,每个新行都被转换为 XML 新行。如果您只关心查看并将其转换为字符串,则可以使用 scala.xml.PrettyPrinter:

val printer = new PrettyPrinter(100, 2)
printer.format(myDiv)

如果你想从该字符串中获取一个元素,你可以使用 loadString:

XML.loadString(printer.format(myDiv))

但您可能只使用 scala.xml.Utility.trim,就像您说的那样,然后使用 PrettyPrint 打印它。如果适合您的结构,您甚至可以覆盖对象的 toString