Nokogiri XML.children除了实际元素之外还返回格式化元素.怎么避免这个?

Ecn*_*lyr 2 ruby nokogiri ruby-on-rails-3

我有以下XML:

<attributes>
    <intelligence>27</intelligence>
    <memory>21</memory>
    <charisma>17</charisma>
    <perception>17</perception>
    <willpower>17</willpower>
</attributes>
Run Code Online (Sandbox Code Playgroud)

我想解析以下内容:

intelligence: 27, memory: 21, charisma: 17, perception: 17, willpower: 17
Run Code Online (Sandbox Code Playgroud)

当我尝试这段代码时:

def get_attributes(api)
  attributes = []
  api.xpath("//attributes").children.each do |attribute|
    name = attribute.name.tr('^A-Za-z0-9', '')
    text = attribute.text
    attributes << "#{name}: #{text}"
  end
  attributes
end
Run Code Online (Sandbox Code Playgroud)

我得到每个偶数子项的换行数据(因为格式化)的结果:

#(Text "\n      ")
#(Element:0x3ffe166fdb9c { name = "intelligence", children = [ #(Text "20")] })
#(Text "\n      ")
#(Element:0x3ffe166f71ac { name = "memory", children = [ #(Text "25")] })
#(Text "\n      ")
#(Element:0x3ffe166f3818 { name = "charisma", children = [ #(Text "23")] })
#(Text "\n      ")
#(Element:0x3ffe166f0604 { name = "perception", children = [ #(Text "16")] })
#(Text "\n      ")
#(Element:0x3ffe166b52e8 { name = "willpower", children = [ #(Text "15")] })
#(Text "\n    ")
Run Code Online (Sandbox Code Playgroud)

在Nokogiri有一种方法可以跳过这些"仅格式化"的孩子吗?或者我是否必须手动遍历奇数元素?

我期望api.xpath("//attributes").children导航实际的孩子,而不是格式化文本.

mat*_*att 6

children方法将返回目标节点的所有子节点,包括文本节点.如果您只想要所有元素节点子节点,则可以使用以下命令在XPath查询中指定它*:

def attributes(api)
  api.xpath('//attributes/*').each_with_object([]) do |n, ary|
    ary << "#{n.name}: #{n.text}"
  end
end
Run Code Online (Sandbox Code Playgroud)

这将返回一个带有格式的字符串数组name: value,这就是你想要的样子.