I have a unique scenario. There is a web application which is a simulator to check sending of data in XML and getting the data back in xml and verifying few details in xml.

Now the xml data which I am sending has a lot of details. In that xml I will have to insert a parameter which I have defined in my test. I am not able to get, how to send the data as parameter in the xml before sending it.

the xml structre looks like this

id='12345'><version>1.3.4<</version><accno>1234567890</accno>add<address details</> ..........

Now int this xml structure, I have parameterized <accno>1234567890</accno> ... Mean in begin of the script I am declaring accno='1234567890'

Now I want to using accno as parameter in the xml instead of the hard coded value in the xml. Please suggest how to do this.

有帮助吗?

解决方案

I will say editing xml, by regex is a bad idea.

but just to answer the direct question use gsub. eg.

str.gsub(/reg_match/, newstring)

but better way of doing it will be use of hpricot,

Or you can also use ruby templates.

require 'erb'
require 'ostruct'

data = {:accno => "1234567890"}
variables = OpenStruct.new(data)

template = "<id='12345'><version>1.3.4</version><accno><%= accno%></accno>"

res = ERB.new(template).result(variables.instance_eval { binding })
puts res

其他提示

XML is not regular, but context-free. Use a proper parser like Nokogiri instead of regex. See RegEx match open tags except XHTML self-contained tags.

As answer, as requested.

First identify the pattern, then replace it using gsub!

xml_data.gsub! (pattern, replacement)

http://ruby-doc.org/docs/ProgrammingRuby/html/ref_c_string.html#String.gsub_oh

The fast way to do it is with gsub (like Rajkaran says). The right way to do it is rexml or some other xml library. Investment should be related to how much you will use this kind of thing in the future.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top