如何使用 Nokogiri 使空标签自动关闭? [英] How can I make empty tags self-closing with Nokogiri?

查看:28
本文介绍了如何使用 Nokogiri 使空标签自动关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 ERB 中创建了一个 XML 模板.我在导出过程中用数据库中的数据填充它.

I've created an XML template in ERB. I fill it in with data from a database during an export process.

在某些情况下,有一个空值,在这种情况下一个元素可能是空的,就像这样:

In some cases, there is a null value, in which case an element may be empty, like this:

<someitem>

</someitem>

在这种情况下,接收导出的客户端希望将其转换为自关闭标签:

In that case, the client receiving the export wants it to be converted into a self-closing tag:

<someitem/>

我想看看如何让 Nokogiri 做到这一点,但我还没有看到.有人知道如何使用 Nokogiri 使空的 XML 标签自动关闭吗?

I'm trying to see how to get Nokogiri to do this, but I don't see it yet. Does anybody know how to make empty XML tags self-closing with Nokogiri?

正则表达式足以完成我在上面指定的操作,但是客户现在还希望子代都为空的标签能够自闭合.所以这个:

A regex was sufficient to do what I specified above, but the client now also wants tags whose children are all empty to be self-closing. So this:

<someitem>
  <subitem>

  </subitem>
  <subitem>

  </subitem>
</someitem>

...也应该

<someitem/>

我认为这需要使用 Nokogiri.

I think that this will require using Nokogiri.

推荐答案

搜索

<([^>]+)>\s*</\1>

并替换为

<\1/>

在 Ruby 中:

result = subject.gsub(/<([^>]+)>\s*<\/\1>/, '<\1/>')

说明:

<       # Match opening bracket
(       # Match and remember...
 [^>]+  # One or more characters except >
)       # End of capturing group
>       # Match closing bracket
\s*     # Match optional whitespace & newlines
<       # Match opening bracket
/       # Match /
\1      # Match the contents of the opening tag
>       # Match closing bracket

这篇关于如何使用 Nokogiri 使空标签自动关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆