我有以下 XML:
<attributes>
<intelligence>27</intelligence>
<memory>21</memory>
<charisma>17</charisma>
<perception>17</perception>
<willpower>17</willpower>
</attributes>
我想解析以下内容:
intelligence: 27, memory: 21, charisma: 17, perception: 17, willpower: 17
当我尝试这段代码时:
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
我得到每个偶数孩子的换行数据(因为格式化)的结果:
#(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 ")
Nokogiri 中是否有一种方法可以跳过这些“仅格式化”的孩子?还是我必须手动遍历奇数元素?
我希望api.xpath("//attributes").children
导航实际的孩子,而不是格式化文本。