I have an XML file, and I need to replace the text between two tags with a new string
the tags are <<Connecti开发者_运维百科onString>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
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>
Use nokogiri for dealing with XML files. See this for the specific task.
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>'
精彩评论