0

I have an XML file, and I need to replace the text between two tags with a new string the tags are <<ConnectionString>ConnectionString>THE OLD TEXT<<ConnectionString>/ConnectionString>

I need to change this to <<ConnectionString>ConnectionString>MY NEW TEXT<<ConnectionString>/ConnectionString>

I can't seem to find anything online, and see that using regex is a bad idea?

Please note, that this file contains more that 1

<<ConnectionString>ConnectionString>THE OLD TEXT<<ConnectionString>/ConnectionString>

Lines!

Can someone point my in the right direction or an example? Andrew

halfelf
  • 9,737
  • 13
  • 54
  • 63
Andrew D
  • 106
  • 1
  • 14

3 Answers3

2

Nokogiri is great for things like this. See the Nokogiri::Node#content= method

#!/usr/bin/env ruby

require 'nokogiri'

doc = Nokogiri.XML(DATA)             # create a new nokogiri object, this could be a string or IO type (anything which responds to #read)
element = doc.at('ConnectionString') # fetch our element
element.content = "MY NEW TEXT"      # change the content
puts doc #=> <?xml version="1.0"?>\n<ConnectionString>MY NEW TEXT</ConnectionString>


__END__
<ConnectionString>THE OLD TEXT</ConnectionString>
Lee Jarvis
  • 16,031
  • 4
  • 38
  • 40
  • OK, this gets me closing, however (sorry if I'm being dumb) how do I pass my XML document into Nokogiri? Can I just replace DATA with the filename? – Andrew D Sep 30 '11 at 18:38
  • No, replace it with something which responds to the `read` method, or a string. Both `Nokogiri.XML(File.new('foo.xml'))` and `Nokogiri.XML(File.read('foo.xml'))` will work :) (of course it you just passed the filename it would interpret it as an xml string, or fail doing so) – Lee Jarvis Sep 30 '11 at 18:39
0

Use nokogiri for dealing with XML files. See this for the specific task.

Community
  • 1
  • 1
lucapette
  • 20,564
  • 6
  • 65
  • 59
  • I did see a post about using nokogiri but couldn't see from that post, or sadly your post how I work this into what I want? – Andrew D Sep 30 '11 at 18:32
0

I agree in general to use nokogiri over regex in xml but in this case I think it's overkill.

xml = open(xmlfile).read.gsub /<ConnectionString>THE OLD TEXT<\/ConnectionString>/, '<ConnectionString>MY NEW TEXT</ConnectionString>'
pguardiario
  • 53,827
  • 19
  • 119
  • 159