You need to enable JavaScript to run this app. Scala标准XML库:如何移除<loc>标签自动添加的首尾空白
优惠活动
大模型
产品
解决方案
定价
更多

Scala标准XML库:如何移除<loc>标签自动添加的首尾空白

解决Scala标准XML库生成站点地图标签首尾空白问题

问题根源

Scala标准XML库默认使用的PrettyPrinter在处理长度超过阈值的文本节点时,会自动插入换行和缩进空白,这就是标签长文本出现首尾空白的原因——短文本未触发换行逻辑,所以无此问题。而你尝试的xsl:strip-space无效,是因为空白是生成XML时就被插入的,并非解析阶段的空白节点。

解决方案

1. 自定义PrettyPrinter强制保留原文本

直接重写formatText方法,让文本节点原样输出,不添加任何空白:

import scala.xml.{Elem, PrettyPrinter}

// 定义自定义格式化器,文本不做任何空白处理
val sitemapPrinter = new PrettyPrinter(1000, 2) {
  override def formatText(text: String): String = text
}

// 示例生成<loc>元素
val longLoc = <loc>https://example.com/a/very/long/url/path/that/exceeds/the/default/line-length/threshold/for/scala-xml-pretty-printing</loc>

// 输出无空白的XML
println(sitemapPrinter.format(longLoc))

2. 使用toString输出紧凑XML

如果不需要XML的缩进美观,直接调用toString方法,它会输出无额外空白的紧凑XML:

val locElem = <loc>https://example.com/your/long/url/here</loc>
println(locElem.toString())

3. 针对性清理标签的空白

如果需要保留其他元素的缩进格式,仅清理标签的首尾空白,可以遍历XML树处理:

import scala.xml.{Node, Text, Elem}

// 递归遍历XML节点,清理<loc>标签的文本空白
def cleanLocWhitespace(node: Node): Node = node match {
  case Elem(prefix, "loc", attrs, scope, kids@_*) =>
    Elem(prefix, "loc", attrs, scope, true, kids.map {
      case Text(content) => Text(content.trim)
      case child => cleanLocWhitespace(child)
    }: _*)
  case elem: Elem =>
    elem.copy(child = elem.child.map(cleanLocWhitespace))
  case other => other
}

// 示例站点地图
val rawSitemap = <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
                   <url>
                     <loc>  https://example.com/long-url-with-unwanted-spaces  </loc>
                     <lastmod>2024-05-20</lastmod>
                   </url>
                 </urlset>

// 清理后格式化输出
val cleanedSitemap = cleanLocWhitespace(rawSitemap)
val printer = new PrettyPrinter(1000, 2)
println(printer.format(cleanedSitemap))

内容的提问来源于stack exchange,提问作者Max Moroz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 16:36:22