Here’s an example of the data:
<animals><name>George</name><description>A big brown fox.</description></animals>
It really doesn’t get more complicated than that. I want to modify all text in the elements. (In this case, encrypt it).
What I’ve come up with so far is:
xml_data.gsub(/(<.*>)(.+)(<\/.*>)(?=<)/, "#{$1}#{$2.encrypt_string}#{$3}")
But, it only replaces the last element’s text. So I’m obviously missing something.
I invite any suggestions (including using REXML). I must use libraries standard with Ruby 1.8.7.
There is no chance of the XML being malformed because I wrote the process that produces it.
Thank you in advance!
Don’t use regular expressions for this, use a real parser such as Nokogiri:
Assuming of course that you have monkey patched
encrypt_stringinto String somewhere.As far as your regex goes,
(.+)is greedy and will happily consume</close_tag>, you have similar problems with.*.If you must use a regex (and it seems that you have choice), then you should tighten up your regex and switch to the block form of gsub to get sensible
$1and$2:Using
[^>]+and[^<]+keeps you within the tags you want and the\1back-reference is an easy to way match the opening and closing tags. For example, usingupcasein place ofencrypt_stringdoes this: