Ruby XML 替换

发布于 2024-12-07 17:56:49 字数 595 浏览 0 评论 0原文

我有一个 XML 文件,我需要用新字符串替换两个标签之间的文本 标签是 <ConnectionString>THE OLD TEXT</ConnectionString>

我需要将其更改为 <ConnectionString>MY NEW TEXT</ConnectionString>

我似乎在网上找不到任何东西,看看使用正则表达式是一个坏主意?

请注意,该文件包含超过 1

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

行!

有人可以指出我正确的方向或例子吗? 安德鲁

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

萌酱 2024-12-14 17:56:49

Nokogiri 非常适合这样的事情。请参阅 Nokogiri::Node#content= 方法

#!/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>

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>
酒绊 2024-12-14 17:56:49

使用 nokogiri 处理 XML 文件。有关具体任务,请参阅

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

哎呦我呸! 2024-12-14 17:56:49

我一般同意在 xml 中使用 nokogiri 而不是正则表达式,但在这种情况下我认为这是矫枉过正。

xml = open(xmlfile).read.gsub /<ConnectionString>THE OLD TEXT<\/ConnectionString>/, '<ConnectionString>MY NEW TEXT</ConnectionString>'

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>'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文