How can I make empty tags self-closing using Nokogiri?

I created an XML template in ERB. I populate it with data from the database during the export process.

In some cases, a null value exists, in which case the element may be empty, for example:

<someitem>

</someitem>

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

<someitem/>

I’m trying to figure out how to get Nokigiri to do this, but I don’t see it yet. Does anyone know how to make self-closing XML tags using Nokogiri?

Update

The regular expression was sufficient to accomplish what I indicated above, but now the client also wants the tags whose children were empty to be self-closing. So:

<someitem>
  <subitem>

  </subitem>
  <subitem>

  </subitem>
</someitem>

... should also be

<someitem/>

I think this will require the use of Nokogiri.

+5
2

<([^>]+)>\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
+5

:

  • <foo></foo> <foo />, ? , node - "\n", ERB, , , , ? . " ".
  • ? XML ERB, .

EDIT - Nokogiri , XML, . , node, node, Nokogiri , .

+1

All Articles