次の 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
書式設定テキストではなく、実際の子をナビゲートする ことを期待しています。