使用 Rails 和 Nokogiri 修改具有多个文本的 XML

发布于 2025-01-01 14:28:31 字数 392 浏览 3 评论 0原文

我正在寻找可以修改 Ruby 中的 .docx 文件的东西。在这里,在这段代码中我对 xml 文件进行了修改。

仅修改一次元素,但想将所有元素 "FirstName" 替换为 "DEMONAME"

doc = Nokogiri::XML(IO.read('word/document.xml'))
doc.at('//text()[.="FirstName"]').content = 'DEMONAME'
File.open('word/document_modify.xml','w') do |f|
  f.puts doc
end

请建议修改整个文档 5 次或更多次 名字

I am looking for something which will modify the .docx file in Ruby. Here, in this code I have done with modification in xml file.

Only once element is modified , but wanna replace all the element "FirstName" with "DEMONAME"

doc = Nokogiri::XML(IO.read('word/document.xml'))
doc.at('//text()[.="FirstName"]').content = 'DEMONAME'
File.open('word/document_modify.xml','w') do |f|
  f.puts doc
end

Please suggest some thing to modify whole document having 5 times or more times FirstName.

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

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

发布评论

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

评论(1

对不⑦ 2025-01-08 14:28:31

最后我找到了解决这个问题的方法。

doc = Nokogiri::XML(IO.read('word/document.xml'))
(doc/'//text()[.="FirstName"]').each do |field|
  doc.at('//text()[.="FirstName"]').content = 'DEMONAME'
end

At last I got the solution to resolve this problem.

doc = Nokogiri::XML(IO.read('word/document.xml'))
(doc/'//text()[.="FirstName"]').each do |field|
  doc.at('//text()[.="FirstName"]').content = 'DEMONAME'
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文