【问题标题】:Parsing XML in Ruby using a recursive function使用递归函数在 Ruby 中解析 XML
【发布时间】:2014-08-05 14:03:00
【问题描述】:

我正在尝试更改以下 XML 文件中的数据。我确信数据将在<string> 标签中但在其中可以嵌套到任何程度的一件事。所以为了做到这一点,我想出了一个递归解决方案,它看起来像是正确的代码,但没有做任何改变。

C 或 C++ 中的递归很容易,因为更改很容易反映在实际参数中,但在 Ruby 中,我无法弄清楚如何反映这一点。

源 XML:

<document>
  <string id="title">Continue without CableCARD?</string>
  <string id="bodytext"/>
  <string id = "f" >This is data1
    <p>
      <t>
        this is data2
      </t>
    </p>
    this is data3
  </string>
</document>

Ruby 代码:

require 'nokogiri'

doc = Nokogiri::XML(File.open("d.xml"))
def rec_func(s)
  if s.child.class == NilClass
    return s
  end
  array = s.children()
  array.each do |element|
    if element == Nokogiri::XML::Text
      s.content = s.content + "A"
    else
      element =  rec_func(element)
      puts "##########"
      puts element
    end
  end
  s.children = array # I added this statement as I was in doubt whether the changes in this array will be reflected in the parent s or not.

  return s
end
doc.xpath("//string").each do |node|
  k = rec_func node
  puts "$$$$$$$$$$$$$$"
end

请有人建议对代码进行任何更改以使其正常工作。

【问题讨论】:

  • 首先,条件element == Nokogiri::XML::Text 不起作用。 element 不等于它的类......你可能想这样做:Nokogiri::XML::Text === element
  • 它也不起作用

标签: ruby recursion nokogiri


【解决方案1】:

给你。我用递归方法parse_children 解析“//string”的每个孩子。在这个方法中,我遍历所有的孩子,对于一个特定的孩子,我检查它是否是XML::Text。如果是,这将结束递归(并对这个文本做一些事情)。如果没有,则使用此元素的子级递归调用 parse_children

def parse_children(children)
  children.each do |child|
    case child
    when Nokogiri::XML::Text
      child.content = child.content.strip + "A"
    when Nokogiri::XML::Element
      parse_children child.children
    end
  end
end

doc = Nokogiri::XML.parse(xml)
doc.xpath('//string').each do |s|
  parse_children s.children
end

puts doc.to_xml

【讨论】:

  • 它工作不正常,但我对其进行了修改以完成工作!谢啦!!文档中的更改未反映在实际的 xml 文件中。请告诉我如何让更改反映在 xml 文件中。
  • 我不知道 正常工作 是什么意思,但我的代码可以解决问题:在每个 XML::Text 的末尾添加字母“A”。
  • 是的,我同意,但代码还在

    标记之间添加了一个“A”,这是不需要的。但主要问题是更改没有反映在源xml文件中

  • 我有一个小问题..就像上面一样,我在代码中递归遍历 xml 文件,而我正在重写文档丢失缩进的数据.. 这是 nokogiri 的问题吗?如何解决这个问题.. 我的意思是当我们递归遍历 xml 文档时如何保持缩进
  • 这里stackoverflow.com/questions/1898829/…是格式化问题的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-19
  • 1970-01-01
  • 2022-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多