Reputation: 503
I have an xml document with fragments like the following:
<x>
abcd
<z>ef</z>
ghij
</x>
I want to find the text "defg" inside the node, and modify that node to the following:
<x>
abc
<y>
d<z>ef</z>g
</y>
hij
</x>
This means creating a new node that has bit of x.text and other children inside.
I can find the node which includes the text, but I don't know how to break it up, and wrap just the matching section inside the <y>
tags.
Any ideas that can point me in the right direction are most appreciated. Thanks.
Upvotes: 1
Views: 424
Reputation: 8835
What about turning it into a sting and then use a regex to change it, and then parse it with nokogiri again.
sting = some_xml.to_s
# => '<x>abcd<z>ef</z>ghij</x>'
splits = sting.match(/(.)<z>(.*)<\/z>(.)/)
new_string = sting.gsub(splits[1], "<y>#{splits[1]}").gsub(splits[3], "#{splits[3]}</y>")
Nokogiri::XML(new_string)
Upvotes: 1