从 XML 标记内的多行中删除空格

Posted

技术标签:

【中文标题】从 XML 标记内的多行中删除空格【英文标题】:Get rid of white spaces from multiline inside XML tag 【发布时间】:2021-09-13 06:05:31 【问题描述】:

我有这个 XML 块:

 <context id="134">Multiline incoming: 
    This is my 1st line. 
    This is my 2nd line. 
    This is my 3rd line. 
 </context> 

有没有办法使用任何 XML 解析库(如 Perl 中的 LibXML)自动删除间距?我可以手动摆脱它们,但我很感兴趣是否已经有这种方法。

我希望我的输出是:

$context = "Multiline incoming: This is my 1st line. This is my 2nd line. This is my 3rd line." 

【问题讨论】:

没有。空格是有意义的,但您可以使用正则表达式或 CPAN 中的各种文本修剪模块之一。 【参考方案1】:

你只需要这个:

$context =~ s/^\s+//;          # Remove leading whitespace
$context =~ s/\s*\v\s*/ /g;    # Replace whitespace that includes vertical whitespace 
$context =~ s/\s+\z//;         # Remove trailing whitespace

【讨论】:

以上是关于从 XML 标记内的多行中删除空格的主要内容,如果未能解决你的问题,请参考以下文章