删除 XML 标签中的空格
我正在尝试编写一个 perl 脚本,从 XML 标记中删除空格,但在值内保留空格。例如,假设我有:
<Example>This is an example.</Exampl e>
我想要完成的是专门删除 中的空白。由于这将在整个 XML 文档上工作,所以我想我应该使用替换运算符做一些事情,但我不太清楚如何只匹配可能位于 XML 标记本身内部的空白。
非常感谢任何帮助!
编辑:我添加了一个正在发生的事情的真实示例:
not well-formed (invalid token) at line 42, column 25, byte 1456:
<Artist>Eminem</Artist>
<FileName>eminem feat lil wayne - no love -
hotnewhiphop com(2).mp3</ FileName>
========================^
<FileSize>4804478</FileSize>
I'm trying to write a perl script that removes whitespace from XML tags, but leaves whitespace inside of the values. For example, let's say I have:
<Example>This is an example.</Exampl e>
What I'm looking to accomplish is to knock off the whitespace specifically in </Exampl e>
. Since this will be working on an entire XML document, I figured I'd do something with the substitution operator, but I can't quite figure out how to only match whitespace that might be inside of the XML tags themselves.
Any help is greatly appreciated!
Edit: I've added a real example of what is occurring:
not well-formed (invalid token) at line 42, column 25, byte 1456:
<Artist>Eminem</Artist>
<FileName>eminem feat lil wayne - no love -
hotnewhiphop com(2).mp3</ FileName>
========================^
<FileSize>4804478</FileSize>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您实际上想在带有属性的标签中保留空格,情况会变得更加复杂,因为空格是标签中的合法字符。您几乎必须找到后面没有等号或空格+等号的“单词”,并将它们与前一个(未引用)单词结合起来。
e
标志意味着您正在*eval
*-替换部分。If you want to actually leave whitespace in a tag with attributes, it gets more complex, because whitespace is a legitimate character in a tag. You pretty much have to find the "words" with no equals or space + equals after them and marry them to the previous--unquoted--word.
The
e
flag means that you are*eval
*-ing in the replacement part.我强烈建议您避免滚动自己的 XML 解析,或尝试通过正则表达式等操作 XML。
使用众多可用的 XML 解析器之一,这样可以避免麻烦。
例如,查看 XML::Easy、XML::Smart, XML::TreeBuilder, XML::Twig 。
另请参阅 http://perl-xml.sourceforge.net/faq/ 以获得相当全面的信息有关使用 Perl 处理 XML 的常见问题解答。
I'd strongly recommend avoiding rolling your own XML parsing, or trying to manipulate the XML via regexes etc.
Use one of the many XML parsers available, and save yourself the headaches.
For instance, look at XML::Easy, XML::Smart, XML::TreeBuilder, XML::Twig.
See also http://perl-xml.sourceforge.net/faq/ for a pretty comprehensive FAQ on handling XML with Perl.