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

后端 未结 2 1811
别跟我提以往
别跟我提以往 2021-01-18 23:18

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

2条回答
  •  情歌与酒
    2021-01-18 23:54

    Search for

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

    and replace with

    <\1/>
    

    In Ruby:

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

    Explanation:

    <       # 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
    

提交回复
热议问题